【问题标题】:XPath: How do I find the parent element and its class for all text nodesXPath:如何找到所有文本节点的父元素及其类
【发布时间】:2013-02-06 04:22:40
【问题描述】:

对于所有的文本节点,如何找到父元素的类和标签类型

【问题讨论】:

  • 您能添加您尝试过的示例 xml 和代码吗?

标签: python html xml xpath lxml


【解决方案1】:

XPath documentation,没那么难。这是我的专用 XML 文件:

<root>
    <child1>
        <text>Text1</text>
    </child1>
    <child2>
        <text>Text2</text>
    </child2>
    <child3>
        <text>Text3</text>
    </child3>
    <child4>
        <text>Text4</text>
    </child4>
</root>

现在有了实现 XPath 支持的 lxml lib(内置 Python XML 库不是这种情况),我们在这里:

>>> from lxml import etree
>>> root = etree.parse(path).getroot()
>>> for p in root.xpath('//text/..'):
    print p.tag


child1
child2
child3
child4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2021-07-16
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多