且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-14 15:19:22

这里有一个 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.x3.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.