检索一个元素的所有文本,包括其python中的子元素

问题描述:

我编写了一个代码来查找xml中特定标记中的文本。它适用于没有子标签的标签。检索一个元素的所有文本,包括其python中的子元素

For e.g. 1 <a>ajsaka</a>. it works fine for this. 

e.g. 2 But if there is an instance of <b>ahsjd<c>jjiij</c>aa</b>. 

它不工作。我希望标签中的所有内容包括其子元素文本。我想要它打印ahsjdjjiijaa,但它只打印ahsjd。这是我的代码到目前为止。

这里是输入文件。

<level> 
<ex> 
<nt>[edit <topic-ref link-text="short-title" 
topic-id="13629">address</topic-ref>],</nt> 
<nt>[edit routing-instances <var>routing-instance-name</var 
    > <topic-ref link-text="short-title" topic-id="13629">address- 
assignment</topic-ref 
>]</nt> 
</ex> 
    <exam> 
    </exam> 
</level> 

from lxml import etree 
doc=etree.parse('C:/xx/bb.xml') 
root=doc.getroot() 
node=root.find('level') 
count=len(node.getchildren()) 
print (count) 
for elem in root.findall('level/ex/nt'): 
    print (elem.text) 

我该如何得到它?

+0

这里没有'你输入XML中level'标签。扩展您的输入 – RomanPerekhrest

你可以阅读您的文件作为字符串,然后concatinate标签

之间的所有文字
import xml.etree.ElementTree as ET 
text = open('C:/xx/bb.xml').read() 
''.join(ET.fromstring(text).itertext()) 

输出:

'ahsjdjjiijaa' 
+0

它工作时,我想我的文件中的所有内容作为一个字符串?心不是。对不起,如果我错了。即使内部有子标签,我也只想要特定标签内的内容。 (''.join([x for elem.itertext()])) 它的工作原理是在root.findall('hierarchy-level/example/statement')中为elem编写的代码 –

+0

。谢谢。现在我明白了。 –