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

2024-05-19 15:05:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个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来获取它的正确方法应该是什么呢?


Tags: 文件namedevuuidosdomaintypeunit
3条回答

etree,用lxml可能:

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

这里有一个lxml片段,它提取属性和元素文本(您的问题有点含糊不清,所以我将两者都包括在内):

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是否是一个好的选择。下面是使用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

<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

相关问题 更多 >