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
3
  • What have you done so far? What are you using to parse the XML? Commented Apr 21, 2014 at 11:58
  • Which bit are you stuck with. Xml or XPath. Show us some code. Commented Apr 21, 2014 at 11:58
  • Please find the answer here, if you wanna use xpath stackoverflow.com/questions/5093002/… Commented Apr 19, 2017 at 16:44

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.