Return XPath attribute value with ElementTree

倖福魔咒の 提交于 2020-01-05 04:01:06

问题


I want to evaluate XML documents with this kind of structure:

<?xml version="1.0" encoding="UTF-8"?>
<Service_name version="3.3.0">
...

where Service_name tag name is not constant string, while version attribute is required.

For that purpose this xpath expression: /*[1]/@version evaluates fine with any xpath processor, but I can't figure how with Python ElementTree.

For example:

import xml.etree.ElementTree as ET
doc = ET.parse('sample.xml')
v = find('/*[1]/@version').text

raises KeyError: '@'

I tried similar combinations but none that worked.

How can I get version number from above example document with ElementTree?


回答1:


ElementTree uses its own path syntax, which is more or less a subset of xpath. If you want an ElementTree compatible library with full xpath support, try lxml.




回答2:


Although it's not XPath as question name, this seems like one way:

doc.getroot().get('version')



来源:https://stackoverflow.com/questions/12209092/return-xpath-attribute-value-with-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!