我必须解析包含类似条目的 xml 文件
<error code="UnknownDevice">
<description />
</error>
在别处定义为
<group name="error definitions">
<errordef id="0x11" name="UnknownDevice">
<description>Indicated device is unknown</description>
</errordef>
...
</group>
给定
import xml.etree.ElementTree as ET
parser = ET.XMLParser()
parser.parser.UseForeignDTD(True)
tree = ET.parse(inputFileName, parser=parser)
root = tree.getroot()
如何获取 errorDef
的这些值?我的意思是 id
和 description
的值?
如何使用 unknownDevice
搜索并提取这些值?
[更新] 错误组具有不同的名称,但格式始终为“XXX 错误定义”、“YYY 错误定义”等
此外,它们似乎嵌套在不同文档中的不同深度。
给定错误标题,例如“unknownDevice”,我如何搜索根目录下的所有内容以获取相应的 id
和 description 值?
我可以使用“unknownDevice”等直接访问它们,还是必须先搜索错误组?
最佳答案
如果你有这个:
<group name="error definitions">
<errordef id="0x11" name="UnknownDevice">
<description>Indicated device is unknown</description>
</errordef>
...
</group>
并且您想要获取每个 errordef
元素的 description
和 id
的值,您可以这样做:
for err in tree.xpath('//errordef'):
print err.get('id'), err.find('description').text
这会给你类似的东西:
0x11 Indicated device is unknown
关于python - 使用 xml.etree.ElementTree 解析 XML 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31591944/