【问题标题】:How to get the text between tags in a xml, using preferably lxml如何获取xml中标签之间的文本,最好使用lxml
【发布时间】:2018-01-12 18:57:06
【问题描述】:

这是标签的一个例子,但我无法获取标签之间的文本,不能遍历标签,不能使用节点 <seg> 中的 node.text。这就是我问的原因,欢迎所有帮助(对不起我的英语)。

    <tuv>
         <seg>If you want to save items in a 
            <bpt i="1">&lt;Message id=&quot;Message:1T0000772343:f000012900ce8eb3:MPhS&quot;&gt;</bpt>
            <ept i="1">&lt;/Message&gt;</ept> 
            for which no connection has been established or in a 
            <bpt i="2">&lt;Message id=&quot;Message:1T0000772343:f000012900ceac3d:pvy4&quot;&gt;</bpt>
            <ept i="2">&lt;/Message&gt;</ept> 
            that requires authentication, you need to connect to the library.
         </seg>
   </tuv>

想要的输出:

如果您想将项目保存在尚未建立连接或需要身份验证的 a 中,则需要连接到库。

【问题讨论】:

    标签: python xml xml-parsing lxml


    【解决方案1】:

    &lt;seg&gt; 元素上使用.xpath("text()") 以获取所有文本节点。

    此代码打印所需的输出:

    from lxml import etree
    
    root = etree.parse("tuv.xml")  
    seg = root.find("seg")
    
    # Get the text nodes of 'seg' as one string
    text = " ".join(t for t in seg.xpath("text()"))
    
    # Print result with unwanted whitespace removed
    print " ".join(text.split())
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多