检索元素的所有文本,包括其在Python中的孩子



我写了一个代码,以在XML中的特定标签中找到文本。它适用于没有子标签的标签。

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)

我如何获得它?

您可以将文件读为字符串,然后将所有文本限制在标签之间

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

输出:

'ahsjdjjiijaa'

相关内容

最新更新