python - 如何简化我的代码 - 提取相同 xml 标记名称的所有节点值

标签 python xml minidom

例如,以下是 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/

相关文章:

安卓|找不到以下类 : menu and item

python - python 中的 xml 缺少元素

android - 如何解决Android资源链接失败错误?

python - 跨多行贪婪分割

python - 在 Pandas 中组合系列

python - Python有没有好的依赖分析工具?

使用 xmllint 进行 XML 架构验证 : complains about empty tags like <foobar/>

python - minidom python 上的 XML 缩进

python - 将命名空间添加到 DOM 元素 python

python - 根据 python 性能决定博客 URL 方案