简体   繁体   English

python解析xml:从包含标签中获取文本

[英]python Parsing xml: get text from tag which contains <i> or <b> or similar

I'm using xml.etree.ElementTree.我正在使用 xml.etree.ElementTree。 When I try to get text from AbstractText, I get None or partial text if there are formatting tags like i, b or similar tags into the text.当我尝试从 AbstractText 获取文本时,如果文本中有像 i、b 或类似标签这样的格式标签,我会得到 None 或部分文本。

Here is a xml example这是一个xml示例


<root>  
    <AbstractText><b>1.</b>  test text <b> 2. </b> is very silly.</AbstractText>
    <AbstractText>hello <b> this is </b> another example </AbstractText>    
</root>

python code is python代码是

tree = ET.parse("xml/test.xml")
root =tree.getroot()
for node in root.findall('AbstractText'):
print(node.text)

and the output is输出是

None
hello 

How can I fix it?我该如何解决? I want all the text without i, b, or other information我想要所有没有 i、b 或其他信息的文本

Here a example这里有一个例子

import xml.etree.ElementTree as ET
from lxml import etree

tree = etree.parse('file.xml')
for node in tree.findall('AbstractText'):
    #print(node)
    print(etree.tostring(node, encoding='utf8', method='text'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM