Created
September 2, 2015 16:03
-
-
Save efaisal/6b857c8e97011ff53140 to your computer and use it in GitHub Desktop.
Example on how to process XML using lxml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Sample taken from http://www.w3schools.com/xml/simple.xml | |
""" | |
from StringIO import StringIO | |
from lxml import etree | |
# Open XML file | |
myxml = etree.parse('simple.xml') | |
xml_object = myxml.getroot() | |
# Add extra <food/> - Roti Canai | |
# Subelements for <foods/> are <name/>,<price/>,<description/> & <calories/> | |
roti_canai = etree.Element('food') | |
etree.SubElement(roti_canai, 'nama').text = 'Roti Canai' | |
etree.SubElement(roti_canai, 'price').text = '$1.99' | |
etree.SubElement(roti_canai, 'description').text = 'The cornerstone of Malaysian diet' | |
etree.SubElement(roti_canai, 'calories').text = '1500' | |
xml_object.append(roti_canai) | |
# Output to standard output | |
#print etree.tostring(xml_object, method='xml', encoding='UTF-8') | |
# Write to file | |
myxml.write('contoh.xml', encoding='UTF-8', xml_declaration=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment