【问题标题】:Retrieve all text of an element including its child in python在python中检索元素的所有文本,包括其子元素
【发布时间】:2017-06-22 12:27:18
【问题描述】:

我编写了一个代码来查找 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)

我如何获得它?

【问题讨论】:

  • 您的输入 xml 中没有 level 标记。扩展您的输入

标签: xml python-3.x elementtree xml.etree


【解决方案1】:

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

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

输出:

'ahsjdjjiijaa'

【讨论】:

  • 当我希望文件中的所有内容都作为字符串时,它可以工作吗?不是。对不起,如果我错了。我只想要特定标签内的内容,即使它里面有子标签。
  • for elem in root.findall('hierarchy-level/example/statement'): print ("".join([x for x in elem.itertext()])) 它起作用了。谢谢。现在我明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 2015-02-16
  • 1970-01-01
相关资源
最近更新 更多