使用 xml.etree.ElementTree 解析 XML 文件时出现问题

Problems parsing an XML file with xml.etree.ElementTree

我必须解析 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 的这些值?我的意思是 iddescription?

的值

如何使用 unknownDevice 搜索和提取这些值?


[更新] 错误组有不同的名称,但格式始终为 "XXX error definitions"、"YYY error definitions" 等

此外,它们似乎嵌套在不同文档中的不同深度。

鉴于错误的标题,例如 "unknownDevice",我如何搜索根目录下的所有内容以获取相应的 iddescription values?

我可以直接找到他们,例如使用 "unknownDevice",还是我必须先搜索错误组?

您需要一个 selector,尽管我不确定您是否可以使用 lxml 来做到这一点。它有 css select 或者但我在文档中找不到 select 和 "id" 的任何内容... 我只使用 lxml 到 remove/add 东西到 html。也许看看scrapy?使用 scrapy 加载 html.

时它看起来像这样
response.xpath('//div[@id="0x11"]/text()').extract()

首先,将错误定义解析成字典:

errors = {
    errordef.attrib["name"]: {"id": errordef.attrib.get("id"), "description": errordef.findtext("description")}
    for errordef in root.xpath(".//group[@name='error definitions']/errordef[@name]")
}

然后,每次需要获取error id和description的时候,通过代码查找:

error_code = root.find("error").attrib["code"]
print(errors.get(error_code, "Unknown Error"))

请注意 xpath() 方法来自 lxml.etree。如果您使用 xml.etree.ElementTree,请将 xpath() 替换为 findall() - xml.etree.ElementTree 提供的有限 XPath 支持足以满足提供的表达式。

如果你有这个:

<group name="error definitions">
     <errordef id="0x11" name="UnknownDevice">
        <description>Indicated device is unknown</description>
     </errordef>
     ...
</group>

并且您想为每个 errordef 元素获取 descriptionid 的值,您可以这样做:

for err in tree.xpath('//errordef'):
    print err.get('id'), err.find('description').text

这会给你类似的东西:

0x11 Indicated device is unknown

你想得到每个errordef元素的描述和id的值,你可以这样做:

import xml.etree.ElementTree as ET
dict01={}
tree=ET.parse('grpError.xml')
root=tree.getroot()
print (root)
docExe=root.findall('errordef') #Element reference
dict01=docExe[0].attrib #Store Attributes in dictionary
print (dict01)
print (dict01['id']) #Attributes of an element
print (dict01['name']) #Attributes of an element
print (docExe[0].find('description').text) #Child Elements inside parent Element

输出为:

<Element 'group' at 0x000001A582EDB4A8>
{'id': '0x11', 'name': 'UnknownDevice'}
0x11
UnknownDevice
Indicated device is unknown