【问题标题】:How do I parse XML with attribute in python? [duplicate]如何在 python 中使用属性解析 XML? [复制]
【发布时间】:2014-06-05 11:47:07
【问题描述】:

我有一个有很多行的 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

【问题讨论】:

  • 到目前为止你做了什么?你用什么来解析 XML?
  • 你坚持哪一点。 Xml 或 XPath。给我们看一些代码。
  • 如果你想使用 xpath stackoverflow.com/questions/5093002/…,请在这里找到答案

标签: python xml


【解决方案1】:

查看标准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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多