Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for renaming XML elements

Tags:

python

xml

I have a XML file where I want to edit or rename elements and save the file. What is the best way to do it. The XML file is given below

<breakfast_menu>
<food>
    <name>Belgian Waffles</name>
    <price>$5.95</price>
    <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
    <calories>650</calories>
</food>
<food>
    <name>Strawberry Belgian Waffles</name>
    <price>$7.95</price>
    <description>light Belgian waffles covered with strawberries and whipped cream</description>
    <calories>900</calories>
</food>
<food>
    <name>Berry-Berry Belgian Waffles</name>
    <price>$8.95</price>
    <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
    <calories>900</calories>
</food>
<food>
    <name>French Toast</name>
    <price>$4.50</price>
    <description>thick slices made from our homemade sourdough bread</description>
    <calories>600</calories>
</food>
<food>
    <name>Homestyle Breakfast</name>
    <price>$6.95</price>
    <description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
    <calories>950</calories>
</food>
</breakfast_menu>

How can I change "description" to "details"?

like image 310
user1138880 Avatar asked Apr 20 '13 14:04

user1138880


1 Answers

I'm suggesting you to use ElementTree to parse your XML document.

This is the simple and the best library to deal with XML docs in python.

Here is an example code:

import xml.etree.ElementTree as xmlParser
xmlDoc = xmlParser.parse('path to your xml doc')
rootElement = xmlDoc.getroot()

for element in rootElement.iter('description'):
    element.tag = 'details'

# Saving the xml
xmlDoc.write('path to your new xml doc')
like image 180
Ori Seri Avatar answered Nov 07 '22 16:11

Ori Seri