【问题标题】:Reading XML file and fetching its attributes value in Python在 Python 中读取 XML 文件并获取其属性值
【发布时间】:2012-08-30 16:24:32
【问题描述】:

我有这个 XML 文件:

<domain type='kmc' id='007'>
  <name>virtual bug</name>
  <uuid>66523dfdf555dfd</uuid>
  <os>
    <type arch='xintel' machine='ubuntu'>hvm</type>
    <boot dev='hd'/>
    <boot dev='cdrom'/>
  </os>
  <memory unit='KiB'>524288</memory>
  <currentMemory unit='KiB'>270336</currentMemory>
  <vcpu placement='static'>10</vcpu>

现在,我想解析它并获取它的属性值。例如,我想获取 uuid 字段。那么在 Python 中获取它的正确方法应该是什么?

【问题讨论】:

  • 你试过什么?谷歌搜索“python xml”会产生很多非常有用的结果,这些结果应该会为您指明正确的方向。
  • 有很多例子,但没有指向我想去的方向。我想获取属性值。我看到的示例是转换为 xml 文件或转换为 xml 文件

标签: python xml xml-parsing python-2.7


【解决方案1】:

etree,可能是lxml

root = etree.XML(MY_XML)
uuid = root.find('uuid')
print uuid.text

【讨论】:

    【解决方案2】:

    我会使用 lxml 并使用 xpath //UUID 解析它

    【讨论】:

      【解决方案3】:

      其他人可以告诉您如何使用 Python 标准库来实现。我会推荐我自己的迷你库,它让这一切变得非常简单。

      >>> obj = xml2obj.xml2obj("""<domain type='kmc' id='007'>
      ... <name>virtual bug</name>
      ... <uuid>66523dfdf555dfd</uuid>
      ... <os>
      ... <type arch='xintel' machine='ubuntu'>hvm</type>
      ... <boot dev='hd'/>
      ... <boot dev='cdrom'/>
      ... </os>
      ... <memory unit='KiB'>524288</memory>
      ... <currentMemory unit='KiB'>270336</currentMemory>
      ... <vcpu placement='static'>10</vcpu>
      ... </domain>""")
      >>> obj.uuid
      u'66523dfdf555dfd'
      

      http://code.activestate.com/recipes/534109-xml-to-python-data-structure/

      【讨论】:

        【解决方案4】:

        这是一个 lxml sn-p,它提取 attribute 以及元素 text(您的问题有点含糊不清)你需要一个,所以我把两者都包括在内):

        from lxml import etree
        doc = etree.parse(filename)
        
        memoryElem = doc.find('memory')
        print memoryElem.text        # element text
        print memoryElem.get('unit') # attribute
        

        您问(在评论 Ali Afshar 的回答中)minidom (2.x, 3.x) 是否是一个不错的选择。这是使用 minidom 的等效代码;自己判断哪个更好:

        import xml.dom.minidom as minidom
        doc = minidom.parse(filename)
        
        memoryElem = doc.getElementsByTagName('memory')[0]
        print ''.join( [node.data for node in memoryElem.childNodes] )
        print memoryElem.getAttribute('unit')
        

        lxml 对我来说似乎是赢家。

        【讨论】:

        • 这个方法也兼容xml.etree.ElementTree,它包含在Python 2和3中。
        • 第一次尝试 lxml 对我不起作用......当我想访问 .text 时,它说 Nonetype 对象没有属性'text'。
        【解决方案5】:

        XML

        <data>
            <items>
                <item name="item1">item1</item>
                <item name="item2">item2</item>
                <item name="item3">item3</item>
                <item name="item4">item4</item>
            </items>
        </data>
        

        Python:

        from xml.dom import minidom
        xmldoc = minidom.parse('items.xml')
        itemlist = xmldoc.getElementsByTagName('item') 
        print "Len : ", len(itemlist)
        print "Attribute Name : ", itemlist[0].attributes['name'].value
        print "Text : ", itemlist[0].firstChild.nodeValue
        for s in itemlist :
            print "Attribute Name : ", s.attributes['name'].value
            print "Text : ", s.firstChild.nodeValue
        

        【讨论】:

          【解决方案6】:

          上面的XML没有结束标签,它会给

          etree 解析错误:标签中的数据过早结束

          正确的 XML 是:

          <domain type='kmc' id='007'>
            <name>virtual bug</name>
            <uuid>66523dfdf555dfd</uuid>
            <os>
              <type arch='xintel' machine='ubuntu'>hvm</type>
              <boot dev='hd'/>
              <boot dev='cdrom'/>
            </os>
            <memory unit='KiB'>524288</memory>
            <currentMemory unit='KiB'>270336</currentMemory>
            <vcpu placement='static'>10</vcpu>
          </domain>
          

          【讨论】:

            【解决方案7】:

            您可以尝试使用 (recover=True) 对其进行解析。 你可以做这样的事情。

            parser = etree.XMLParser(recover=True)
            tree = etree.parse('your xml file', parser)
            

            我最近用过这个,它对我有用,你可以试试看,但如果你需要做更复杂的 xml 数据提取,你可以看看我为某个项目写的这段代码handling complex xml data extractions.

            【讨论】:

              猜你喜欢
              • 2023-03-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-08-18
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-11-11
              相关资源
              最近更新 更多