【问题标题】:Get Element Text Using xml mini dom python使用 xml mini dom python 获取元素文本
【发布时间】:2019-09-11 13:50:26
【问题描述】:

我正在尝试使用mini dom 获取元素的文本,在以下代码中,我还尝试了getText() 建议的方法here,但我无法获得所需的输出,以下是我的代码。我没有从我正在尝试处理的元素中获取 Text 值。

import xml.dom.minidom

doc = xml.dom.minidom.parse("DL_INVOICE_DETAIL_TCB.xml")
results = doc.getElementsByTagName("G_TRANSACTIONS")
def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)
for result in results:
    for element in result.getElementsByTagName("INVOICE_NUMBER"):
        print(element.nodeType)
        print(element.nodeValue)

以下是我的 XML 示例

<LIST_G_TRANSACTIONS>
    <G_TRANSACTIONS>
        <INVOICE_NUMBER>31002</INVOICE_NUMBER>
        <TRANSACTION_CLASS>Invoice</TRANSACTION_CLASS>
    </G_TRANSACTIONS>
</LIST_G_TRANSACTIONS>

我正在使用以下

【问题讨论】:

    标签: python xml python-3.x minidom


    【解决方案1】:

    基于 minidom 的答案

    from xml.dom import minidom
    
    xml = """\
    <LIST_G_TRANSACTIONS>
        <G_TRANSACTIONS>
            <INVOICE_NUMBER>31002</INVOICE_NUMBER>
            <TRANSACTION_CLASS>Invoice1</TRANSACTION_CLASS>
        </G_TRANSACTIONS>
        <G_TRANSACTIONS>
            <INVOICE_NUMBER>31006</INVOICE_NUMBER>
            <TRANSACTION_CLASS>Invoice2</TRANSACTION_CLASS>
        </G_TRANSACTIONS>    
    </LIST_G_TRANSACTIONS>"""
    
    dom = minidom.parseString(xml)
    invoice_numbers = [int(x.firstChild.data) for x in dom.getElementsByTagName("INVOICE_NUMBER")]
    print(invoice_numbers)
    

    输出

    [31002, 31006]
    

    【讨论】:

      【解决方案2】:

      如果你可以使用ElementTree,代码如下:

      import xml.etree.ElementTree as ET
      
      xml = '''<LIST_G_TRANSACTIONS>
          <G_TRANSACTIONS>
              <INVOICE_NUMBER>31002</INVOICE_NUMBER>
              <TRANSACTION_CLASS>Invoice1</TRANSACTION_CLASS>
          </G_TRANSACTIONS>
          <G_TRANSACTIONS>
              <INVOICE_NUMBER>31006</INVOICE_NUMBER>
              <TRANSACTION_CLASS>Invoice2</TRANSACTION_CLASS>
          </G_TRANSACTIONS>    
      </LIST_G_TRANSACTIONS>'''
      
      root = ET.fromstring(xml)
      invoice_numbers = [entry.text for entry in list(root.findall('.//INVOICE_NUMBER'))]
      print(invoice_numbers)
      

      输出

      ['31002', '31006']
      

      【讨论】:

      • 感谢您的回复,但我需要通过 mini dom 获得它
      • 只是让你知道,ElementTree 是一个核心 python 包,而不是一个外部包(就像 minidom)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多