【问题标题】:Parsing XML using lxml, unable to get text when there is another child node使用lxml解析XML,当有另一个子节点时无法获取文本
【发布时间】:2014-09-02 08:45:26
【问题描述】:

我正在使用lxml 解析从 Internet 下载的 XML 文件。它的结构类似于:

<root>
    <a>Some text in A node</a>
    <b><c>Some text in C node</c>Some text in B node</b>
</root>

我想使用以下代码打印节点内的文本:

from lxml import etree
doc = etree.parse('some.xml')
root = doc.getroot()
for ch in root:
    print ch.text

输出

Some text in A node
None

这不是为&lt;B&gt; 打印text。为什么?当我更改 XML(如下所示)时,text 先是子节点,然后是子节点,我得到了正确的输出。它与 XML 语法或 lxml 有关吗?由于我无法控制 XML,因为它是直接从 Internet 下载的,因此我需要一种方法来获取以前格式的文本。

<root>
    <a>Some text in A node</a>
    <b>Some text in B node<c>Some text in C node</c></b>
</root>

输出

Some text in A node
Some text in B node

【问题讨论】:

    标签: python xml python-2.7 lxml


    【解决方案1】:

    根据lxml.etree._Element documentation

    text 属性返回第一个子元素之前的文本。如果没有文本,则这是一个字符串或值 None。

    要打印标签中的任何第一个文本,请尝试使用 xpath 获取子文本节点:

    for ch in root:
        print next((x for x in ch.xpath('text()')), None)
    

    或:

    for ch in root.xpath('/text()'):
        print ch
    

    【讨论】:

    • 是的,文档是这样说的。使用xpath() 获取文本,无论它放在哪里。谢谢。
    猜你喜欢
    • 2014-11-15
    • 2021-09-07
    • 2020-05-13
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多