使用ElementTree返回XPath属性值 [英] Return XPath attribute value with ElementTree
问题描述
我想用这种结构评估XML文档:
I want to evaluate XML documents with this kind of structure:
<?xml version="1.0" encoding="UTF-8"?>
<Service_name version="3.3.0">
...
其中 Service_name
标签名称不是常量字符串,而需要 version
属性。
where Service_name
tag name is not constant string, while version
attribute is required.
为此,此xpath表达式: / * [1] / @ version
在任何xpath处理器上都可以很好地评估,但是我不知道如何使用Python ElementTree。
For that purpose this xpath expression: /*[1]/@version
evaluates fine with any xpath processor, but I can't figure how with Python ElementTree.
例如:
import xml.etree.ElementTree as ET
doc = ET.parse('sample.xml')
v = find('/*[1]/@version').text
引发 KeyError:'@'
我尝试了类似的组合,但没有一个奏效。
I tried similar combinations but none that worked.
如何使用ElementTree从上述示例文档中获取版本号?
How can I get version number from above example document with ElementTree?
推荐答案
ElementTree使用自己的路径语法,该语法或多或少是xpath的子集。如果您想要具有完全xpath支持的ElementTree兼容库,请尝试 lxml 。
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.
这篇关于使用ElementTree返回XPath属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!