我有这个
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>
解决方法
这是一个提取属性和元素文本的
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(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似乎是我的赢家.