例如,以下是 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
虽然它有效,但我想简化代码。如何使用更短的代码实现相同的结果?
最佳答案
您可以使用列表推导式来简化两个 for
循环:
import xml.dom.minidom
node = xml.dom.minidom.parseString(xml_file.text).documentElement
reportLists = node.getElementsByTagName('reportList')
reports = [report.getElementsByTagName('reportName')[0] for report in reportLists]
node_data = [node.data for report in reports for node in report.childNodes if node.nodeType == node.TEXT_NODE]
node_data
现在是一个包含您要打印的信息的列表。
关于python - 如何简化我的代码 - 提取相同 xml 标记名称的所有节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53554035/