Wednesday, October 31, 2018

How do I parse XML with attribute in python?




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:





Pesto Chicken Sandwich
$7.50



Chipotle Chicken Pizza
$12.00


Burrito
$6.20





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

Answer



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

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...