【发布时间】:2019-05-02 09:39:46
【问题描述】:
例如,这里是 XML 数据:
<SOAP-ENV:Body>
<reportList>
<reportName>report 1</reportName>
</reportList>
<reportList>
<reportName>report 2</reportName>
</reportList>
<reportList>
<reportName>report 3</reportName>
</reportList>
</SOAP-ENV:Body>
这是我提取所有reportName的节点值的代码,它可以工作。
import xml.dom.minidom
...
node = xml.dom.minimom.parseString(xml_file.text).documentElement
reportLists = node.getElementsByTagName('reportList')
reports = []
for reportList in reportLists:
reportObj = reportList.getElementsByTagName('reportName')[0]
reports.append(reportObj)
for report in reports:
nodes = report.childNodes
for node in nodes:
if node.nodeType == node.TEXT_NODE:
print (node.data)
结果:
report 1
report 2
report 3
虽然它有效,但我想简化代码。如何使用更短的代码达到同样的效果?
【问题讨论】: