加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 23:27:19 所属栏目:百科 来源:网络整理
导读:我有这个 XML文件: domain type='kmc' id='007' namevirtual bug/name uuid66523dfdf555dfd/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/c
我有这个 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似乎是我的赢家.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读