1

I have an xml which has many number of rows. For a particular given attribute id, the element name and price value should be queried. For instance, my tree looks like:

<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>

How can I get the name and price value of an particular id(1 or 2 or 3)?

I tried minidom for parsing. My code is:

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':
     ????????????????????

And am unable to retrieve the name and price tag value. I checked lot of examples and none satisfied.

It Worked. Code is as follows:

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
Ravi Kumar
  • 339
  • 2
  • 11
  • 24

1 Answers1

1

Check out the standard etree library. It allows you to parse an xml file into a Python object called an ElementTree. You can then call various methods on this object, such as .findall("./food/name").

This might get you started:

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)

output:

Pesto Chicken Sandwich
$7.50
fr1tz
  • 8,018
  • 1
  • 12
  • 8