如何在python中解析带属性的XML?
我有一个xml,它有许多行。对于特定的给定属性id,应该查询元素名称和价格值。例如,我的树看起来像:如何在python中解析带属性的XML?,python,xml,Python,Xml,我有一个xml,它有许多行。对于特定的给定属性id,应该查询元素名称和价格值。例如,我的树看起来像: <menu> <food id="1"> <name>Pesto Chicken Sandwich</name> <price>$7.50</price> </food> <food id="2"> <name>Chipotle Chicken Pizza</nam
<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>
我无法检索名称和价格标签值。我检查了很多例子,没有一个满意
成功了。代码如下:
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
看看标准。它允许您将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
到目前为止你做了什么?您使用什么来解析XML?您使用的是哪一位。Xml或XPath。给我们看一些代码。如果你想使用xpath,请在这里找到答案
Pesto Chicken Sandwich
$7.50