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

前端之家收集整理的这篇文章主要介绍了读取XML文件并在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中应该采用什么方法获取它呢?

解决方法

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

猜你在找的XML相关文章