如何用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</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
1 个回答
1
可以看看标准的 etree 库。这个库可以帮助你把一个 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