Skip to main content
 首页 » 编程设计

python 使用 ElementTree 解析 xml 没有给出感兴趣的结果

2024年10月25日898°冷暖

我有一个这样的xml文件

<?xml version="1.0"?> 
<sample> 
    <text>My name is <b>Wrufesh</b>. What is yours?</text> 
</sample> 

我有这样的 python 代码

import xml.etree.ElementTree as ET 
tree = ET.parse('sample.xml') 
root = tree.getroot() 
for child in root: 
    print child.text() 

我只得到

'My name is' as an output. 

我想得到

'My name is <b>Wrufesh</b>. What is yours?' as an output. 

我能做什么?

请您参考如下方法:

您可以使用 ElementTree.tostringlist() 获得所需的输出:

>>> import xml.etree.ElementTree as ET 
>>> root = ET.parse('sample.xml').getroot() 
>>> l = ET.tostringlist(root.find('text')) 
>>> l 
['<text', '>', 'My name is ', '<b', '>', 'Wrufesh', '</b>', '. What is yours?', '</text>', '\n'] 
>>> ''.join(l[2:-2]) 
'My name is <b>Wrufesh</b>. What is yours?' 

我想知道这对于通用用途来说有多实用。