Python元素树-根据属性的值选择嵌套的xml元素



我正试图根据属性的值选择一个嵌套元素

from xml.etree import ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Report>
<h1>
<h2>
<Element name='Bob' age='32' title='President'></Element>
<Element name='Sue' age='25' title='Vice-President'></Element>
<Element name='Mary' age='44' title='Secretary'></Element>
</h2>
</h1>
</Report>'''
root = ET.fromstring(xml)
element = root.findall("//*[@title='President']")

但是对于元素变量分配,我得到了以下错误

SyntaxError: cannot use absolute path on element

如何仅提取President元素的属性数据?

你非常接近:-(

下面的工作原理-看看xpath中的点。。

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Report>
<h1>
<h2>
<Element name='Bob' age='32' title='President'></Element>
<Element name='Sue' age='25' title='Vice-President'></Element>
<Element name='Mary' age='44' title='Secretary'></Element>
</h2>
</h1>
</Report>'''
root = ET.fromstring(xml)
elements = root.findall(".//*[@title='President']")
print(elements)

这就是您想要的吗?

from xml.etree import ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<Report>
<h1>
<h2>
<Element name='Bob' age='32' title='President'></Element>
<Element name='Sue' age='25' title='Vice-President'></Element>
<Element name='Mary' age='44' title='Secretary'></Element>
</h2>
</h1>
</Report>'''

root = ET.fromstring(xml)
elements = root.findall(".//*[@title='President']")
for i in elements:
print(i.attrib['name'], i.attrib['age'], i.attrib['title'])

相关内容

  • 没有找到相关文章

最新更新