我正在尝试进行 XML 解析并获取 file_name 和 file_path 的数据,但遇到以下错误,任何人都可以帮助找出原因以及如何解决它?
输入 XML:-
<?xml version="1.0" ?>
<contents>
<build>
<name>modem</name>
<role>modem</role>
<chipset>mms1234</chipset>
</build>
<build>
<name>boot</name>
<role>boot</role>
<chipset>ms1234</chipset>
<device_programmer minimized="true">
<file_name>prog_emmc_house_4567_ddr.elf</file_name>
<file_path>images/comPkg/Msm4567Pkg/Bin64/</file_path>
</device_programmer>
<flash_programmer minimized="true">
</flash_programmer>
</build>
</contents>
代码:-
contents_xml_file = r"device_programmer.xml"
print contents_xml_file
tree = ET.parse(contents_xml_file)
root = tree.getroot()
device_programmer = root.find("device_programmer")
file_name = device_programmer.get('file_name')
print file_name
file_path = device_programmer.get('file_path')
print file_path
错误:-
Traceback (most recent call last):
File "script.py", line 37, in <module>
file_name = device_programmer.get('file_name')
AttributeError: 'NoneType' object has no attribute 'get'
请您参考如下方法:
来自文档:
Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:
这就是为什么
device_programmer = root.find("device_programmer")
返回 None 因为 root 下没有 device_programmer 元素。
您可能应该使用 XPath 语法:
device_programmer = root.find("//device_programmer")
