【问题标题】:How to simplify my code - extract all node values of same xml tag name如何简化我的代码 - 提取相同 xml 标记名称的所有节点值
【发布时间】: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

虽然它有效,但我想简化代码。如何使用更短的代码达到同样的效果?

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    您可以使用列表推导简化两个 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 现在是一个包含您正在打印的信息的列表。

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2020-10-27
      • 2013-01-31
      相关资源
      最近更新 更多