如何使用Python ElementTree提取xml属性

Wil*_*ran 33 python xml xpath elementtree

对于:

<foo>
 <bar key="value">text</bar>
</foo>
Run Code Online (Sandbox Code Playgroud)

我如何获得"价值"?

xml.findtext("./bar[@key]")
Run Code Online (Sandbox Code Playgroud)

引发错误.

unu*_*tbu 48

这将找到一个名为的元素的第一个实例,bar并返回该属性的值key.

In [52]: import xml.etree.ElementTree as ET

In [53]: xml=ET.fromstring(contents)

In [54]: xml.find('./bar').attrib['key']
Out[54]: 'value'
Run Code Online (Sandbox Code Playgroud)


ras*_*hok 8

Getting child tag's attribute value in a XML using ElementTree

Parse the XML file and get the root tag and then using [0] will give us first child tag. Similarly [1], [2] gives us subsequent child tags. After getting child tag use .attrib[attribute_name] to get value of that attribute.

>>> import xml.etree.ElementTree as ET
>>> xmlstr = '<foo><bar key="value">text</bar></foo>'
>>> root = ET.fromstring(xmlstr)
>>> root.tag
'foo'
>>> root[0].tag
'bar'
>>> root[0].attrib['key']
'value'
Run Code Online (Sandbox Code Playgroud)

If the xml content is in file. You should do below task to get the root.

>>> tree = ET.parse('file.xml')
>>> root = tree.getroot()
Run Code Online (Sandbox Code Playgroud)