读取XML文件并在Python中获取其属性值

S.A*_*Ali 4 python xml xml-parsing python-2.7

我有这个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>
Run Code Online (Sandbox Code Playgroud)

现在,我想解析它并获取其属性值.例如,我想获取该uuid字段.那么在Python中应该采用什么方法来获取它呢?

ron*_*man 22

这是一个lxml片段,它提取属性和元素文本(你的问题有点模糊,你需要哪一个,所以我包括两者):

from lxml import etree
doc = etree.parse(filename)

memoryElem = doc.find('memory')
print memoryElem.text        # element text
print memoryElem.get('unit') # attribute
Run Code Online (Sandbox Code Playgroud)

你问(在对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')
Run Code Online (Sandbox Code Playgroud)

lxml似乎是我的赢家.

  • 此方法还与 Python 2 和 3 中包含的 [`xml.etree.ElementTree`](https://docs.python.org/library/xml.etree.elementtree.html) 兼容。 (2认同)

d.d*_*lov 12

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>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)