gpt4 book ai didi

python - 如何在 python 中解析带有属性的 XML?

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:59 26 4
gpt4 key购买 nike

我有一个包含很多行的 xml。对于特定的给定属性 id,应查询元素名称和价格值。例如,我的树看起来像:

<menu>
<food id="1">
<name>Pesto Chicken Sandwich</name>
<price>$7.50</price>
</food>
<food id="2">
<name>Chipotle Chicken Pizza</name>
<price>$12.00</price>
</food>
<food id="3">
<name>Burrito</name>
<price>$6.20</price>
</food>
</menu>

如何获取特定 ID(1 或 2 或 3)的名称和价格值?

我尝试用 minidom 进行解析。我的代码是:

from xml.dom import minidom
xmldoc = minidom.parse('D:/test.xml')
nodes = xmldoc.getElementsByTagName('food')
for node in nodes:
if node.attributes['id'].value == '1':
????????????????????

并且我无法检索名称和价格标签值。我检查了很多例子,但没有一个令人满意。

它起作用了。代码如下:

import xml.etree.ElementTree as ET
tree = ET.parse('D:/test.xml')
root = tree.getroot()
for child in root:
testing = child.get('id')
if testing == '3':
print child.tag, child.attrib
print child.find('name').text
print child.find('price').text

最佳答案

查看标准etree library 。它允许您将 xml 文件解析为称为 ElementTree 的 Python 对象。然后,您可以在此对象上调用各种方法,例如 .findall("./food/name")。

这可能会帮助您开始:

import xml.etree.ElementTree as ET
tree = ET.parse('D:/test.xml')
root = tree.getroot()

def get_info(food_id):
for child in root.findall("*[@id='{0}']//".format(food_id)):
print(child.text)

get_info(1)

输出:

Pesto Chicken Sandwich
$7.50

关于python - 如何在 python 中解析带有属性的 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23196945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com