我有以下xml:
<document>
<internal-code code="201">
<internal-desc>Biscuits Wrapped</internal-desc>
<top-grouping>Finished</top-grouping>
<web-category>Biscuits</web-category>
<web-sub-category>Biscuits (Wrapped)</web-sub-category>
</internal-code>
<internal-code code="202">
<internal-desc>Biscuits Sweet</internal-desc>
<top-grouping>Finished</top-grouping>
<web-category>Biscuits</web-category>
<web-sub-category>Biscuits (Sweets)</web-sub-category>
</internal-code>
<internal-code code="221">
<internal-desc>Biscuits Savoury</internal-desc>
<top-grouping>Finished</top-grouping>
<web-category>Biscuits</web-category>
<web-sub-category>Biscuits For Cheese</web-sub-category>
</internal-code>
....
</document>
Run Code Online (Sandbox Code Playgroud)
我使用以下代码将其加载到树中:
try:
groups = etree.parse(PRODUCT_GROUPS_XML_FILEPATH)
root = groups.getroot()
internalGroup = root.findall("./internal-code")
LOG.append("[INFO] product groupings file loaded and parsed ok")
except Exception as e:
LOG.append("[ERROR] PRODUCT GROUPINGS XML FILE ACCESS PROBLEM")
LOG.append("[***TERMINATED***]")
writelog()
exit()
Run Code Online (Sandbox Code Playgroud)
我想使用 XPath 找到正确的然后能够访问该组的子节点。因此,如果我正在搜索内部代码 221 并想要网络类别,我会执行以下操作:
internalGroup.find("internal-code", 221).get("web-category").text
Run Code Online (Sandbox Code Playgroud)
我对 XML 和 Python 没有经验,而且我一直在关注这个问题多年。非常感谢所有帮助。谢谢
XPath 支持
该模块对用于在树中定位元素的XPath 表达式提供有限的支持。目标是支持缩写语法的一小部分;完整的 XPath 引擎超出了该模块的范围。
使用lxml:
>>> import lxml.etree as ET
>>>
>>> s = '''
... <document>
... <internal-code code="201">
... <internal-desc>Biscuits Wrapped</internal-desc>
... <top-grouping>Finished</top-grouping>
... <web-category>Biscuits</web-category>
... <web-sub-category>Biscuits (Wrapped)</web-sub-category>
... </internal-code>
... <internal-code code="202">
... <internal-desc>Biscuits Sweet</internal-desc>
... <top-grouping>Finished</top-grouping>
... <web-category>Biscuits</web-category>
... <web-sub-category>Biscuits (Sweets)</web-sub-category>
... </internal-code>
... <internal-code code="221">
... <internal-desc>Biscuits Savoury</internal-desc>
... <top-grouping>Finished</top-grouping>
... <web-category>Biscuits</web-category>
... <web-sub-category>Biscuits For Cheese</web-sub-category>
... </internal-code>
... </document>
... '''
>>>
>>> root = ET.fromstring(s)
>>> for text in root.xpath('.//internal-code[@code="221"]/web-category/text()'):
... print(text)
...
Biscuits
Run Code Online (Sandbox Code Playgroud)