如何使用 lxml 从 xml 中提取数据?
How to i extract the data from xml with lxml?
我在从包含 lxml 的 xml 文件中提取数据时遇到问题。我尝试使用 lxml 库提取数据,但我根本没有输出。
from lxml import etree
tree = etree.parse("ifm-00028A-20170711-IODD1.1.xml")
root = tree.getroot()
levels = root.findall('DeviceIdentity', root.nsmap)
for DeviceIdentity in levels:
data_1 = int(DeviceIdentity.find('deviceId').text)
print(data_1)
[IODD][1]
例如,我需要从 vendorId 和 deviceId 中获取值
感谢帮助!
xml 文件的示例
https://i.stack.imgur.com/Ih4Tk.png
这里有两个错误。
首先,findall
findall only searches the immediate descendants of an element if it is given a tag name. You can use XPath表达式进行更深入的搜索。所以你的 findall
应该是
levels = root.findall('.//DeviceIdentity', root.nsmap)
那么,deviceId
就是一个attribute. You should be able to find it in the element's attrib字典。假设您的其余代码是正确的,它看起来像这样:
for DeviceIdentity in levels:
data_1 = int(DeviceIdentity.attrib['deviceId'])
print(data_1)
(在以后的问题中,将示例 XML 作为文本包括在内会有所帮助,并且比 "no output at all" 更具体)
我在从包含 lxml 的 xml 文件中提取数据时遇到问题。我尝试使用 lxml 库提取数据,但我根本没有输出。
from lxml import etree
tree = etree.parse("ifm-00028A-20170711-IODD1.1.xml")
root = tree.getroot()
levels = root.findall('DeviceIdentity', root.nsmap)
for DeviceIdentity in levels:
data_1 = int(DeviceIdentity.find('deviceId').text)
print(data_1)
[IODD][1]
例如,我需要从 vendorId 和 deviceId 中获取值
感谢帮助!
xml 文件的示例 https://i.stack.imgur.com/Ih4Tk.png
这里有两个错误。
首先,findall
findall only searches the immediate descendants of an element if it is given a tag name. You can use XPath表达式进行更深入的搜索。所以你的 findall
应该是
levels = root.findall('.//DeviceIdentity', root.nsmap)
那么,deviceId
就是一个attribute. You should be able to find it in the element's attrib字典。假设您的其余代码是正确的,它看起来像这样:
for DeviceIdentity in levels:
data_1 = int(DeviceIdentity.attrib['deviceId'])
print(data_1)
(在以后的问题中,将示例 XML 作为文本包括在内会有所帮助,并且比 "no output at all" 更具体)