在 Python 中读取 XML 文件并获取其属性值 [英] Reading XML file and fetching its attributes value in Python
问题描述
我有这个 XML 文件:
I have this XML file:
<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 中获取它的正确方法是什么?
Now, I want parse this and fetch its attribute value. For instance, I want to fetch the uuid
field. So what should be the proper method to fetch it, in Python?
推荐答案
这里有一个 lxml 提取属性以及元素文本的片段(您的问题对于您需要哪一个有点含糊不清,所以我将两者都包括在内):
Here's an lxml snippet that extracts an attribute as well as element text (your question was a little ambiguous about which one you needed, so I'm including both):
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 的等效代码;自己判断哪个更好:
You asked (in a comment on Ali Afshar's answer) whether minidom (2.x, 3.x) is a good alternative. Here's the equivalent code using minidom; judge for yourself which is nicer:
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 对我来说似乎是赢家.
lxml seems like the winner to me.
这篇关于在 Python 中读取 XML 文件并获取其属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!