【问题标题】:Search for elements which contains a string in its text or in any of its descendant搜索在其文本或其任何后代中包含字符串的元素
【发布时间】:2020-02-01 03:54:17
【问题描述】:

标题说明了一切。我想搜索所有元素,比如 Node1,它的“Hello World!”出现在其文本或其任何死者中。如果字符串出现在后代中,我仍然想获取 Node1,而不是那个后代。

<?xml version="1.0"?>
<data>
    <Node1 id="Node1">Hello World! from Node1
    </Node1>

    <Node1 id="Node2">Nothing to see here
    </Node1>

    <Node1 id="Node3">
        Some text goes here
        <Node2>
            More text
            <Node3>Hellow World! from Node3 </Node3>
        </Node2>
    </Node1>
</data>

【问题讨论】:

  • 使用lxml,可以查看以下link
  • @Physicing 谢谢,不幸的是,我只能使用普通的 ElementTree
  • 你能发布一个示例 xml 吗?

标签: python xml


【解决方案1】:

ElementTree 我认为你可以做类似的事情

import sys
import xml.etree.ElementTree as etree

s = """<root>
<element>A</element>
  <element2>C</element2>
    <element3>TEST</element3>
<element>B</element>
  <element2>D</element2>
    <element3>Test</element3>
</root>"""

e = etree.fromstring(s)

found = [element for element in e.iter() if element.text == 'Test']

print(found[0])

返回:

<Element 'element3' at 0x7f9edb7e7a98>

参考:

【讨论】:

  • 谢谢。但是这种方法只返回直接节点,例如在我的示例中是 Node3,而不是我要搜索的 Node1。
【解决方案2】:

见下文

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0"?>
<data>
    <Node1 id="Node1">Hello World! from Node1
    </Node1>

    <Node1 id="Node2">Nothing to see here
    </Node1>

    <Node1 id="Node3">
        Some text goes here
        <Node2>
            More text
            <Node3>Hello World! from Node3 </Node3>
        </Node2>
    </Node1>
</data>'''


def scan_node(node, txt, result):
    """
    Scan the node (recursively) and look for the text 'txt'
    :param node:
    :param txt:
    :return:
    """
    children = list(node)
    for child in children:
        if txt in child.text:
            result.append(child)
        scan_node(child, txt, result)


root = ET.fromstring(xml)
result = []
scan_node(root, 'Hello World', result)
print(result)

输出

[<Element 'Node1' at 0x00723A80>, <Element 'Node3' at 0x00723C30>]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 2020-02-23
    • 2020-11-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    相关资源
    最近更新 更多