python使用ElementTree解析xml不会';我不会给出感兴趣的结果

python使用ElementTree解析xml不会';我不会给出感兴趣的结果,python,xml,Python,Xml,我有一个这样的xml文件 <?xml version="1.0"?> <sample> <text>My name is <b>Wrufesh</b>. What is yours?</text> </sample> 我只有 'My name is' as an output. 我想去 'My name is <b>Wrufesh</b>. What is yours?' as

我有一个这样的xml文件

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

'My name is' as an output.
我想去

'My name is <b>Wrufesh</b>. What is yours?' as an output.
“我的名字叫克鲁菲什。“你的是什么?”作为输出。

我能做什么呢?

我认为将xml中的标记作为字符串处理是不对的。您可以访问xml的文本部分,如下所示:

#!/usr/bin/env python
# -*- coding:utf-8 -*- 

import xml.etree.ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
text = root[0]
for i in text.itertext():
    print i

# As you can see, `<b>` and `</b>` is a pair of tags but not strings.
print text._children    
#/usr/bin/env python
#-*-编码:utf-8-*-
将xml.etree.ElementTree作为ET导入
tree=ET.parse('sample.xml')
root=tree.getroot()
text=root[0]
对于文本中的i.itertext():
打印i
#正如您所看到的,``和``是一对标记,但不是字符串。
打印文本

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

>将xml.etree.ElementTree作为ET导入
>>>root=ET.parse('sample.xml').getroot()
>>>l=ET.tostringlist(root.find('text'))
>>>l
['',我的名字是','',Wrufesh','',你的名字是什么?'',''\n']
>>>''.join(l[2:-2])
“我的名字叫沃菲什。你的是什么?”

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

我建议对xml文件进行预处理,将元素包装在
元素下。之后,您应该能够毫无问题地读取这些值

<text><![CDATA[<My name is <b>Wrufesh</b>. What is yours?]]></text>
Wrufesh。你的是什么?]]>

try
child.html()
Element对象没有属性html。如果OP可以预处理文件以包装所需的文本,他还可以当场提取所需的文本,而无需在ElementTree中执行额外的解析和提取数据的步骤。也许我没有说清楚。我的建议是,如果文本元素内的值可以被封装在CDATA中,就像在生成时一样,那么他应该考虑这一点。另一方面,进行全局替换要简单得多!对于我的xml文件,它正在工作,因为每个文本元素都有相同数量的属性。当我在文本元素中有可变数量的属性时,它不会是通用的。在这种情况下,应该通过分析开始和结束标记来计算加入列表的范围
>>> 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?'
<text><![CDATA[<My name is <b>Wrufesh</b>. What is yours?]]></text>