Python Lxml - add existing xml with new data

I am new to python / lxml. After reading the lxml site and plunging into python, I could not find a solution to my n00b problems. I have the following xml example:

--------------- <addressbook> <person> <name>Eric Idle</name> <phone type='fix'>999-999-999</phone> <phone type='mobile'>555-555-555</phone> <address> <street>12, spam road</street> <city>London</city> <zip>H4B 1X3</zip> </address> </person> </addressbook> ------------------------------- 

I am trying to add one child to the root element and write the whole file back as a new xml or more to write the existing xml. Currently, I am writing only one line.

 from lxml import etree tree = etree.parse('addressbook.xml') root = tree.getroot() oSetroot = etree.Element(root.tag) NewSub = etree.SubElement ( oSetroot, 'CREATE_NEW_SUB' ) doc = etree.ElementTree (oSetroot) doc.write ( 'addressbook1.xml' ) 

TIA

+7
python xml lxml
source share
1 answer

You can create a new tree by copying on top of everything old (and not just the root tag!)), But it’s much easier to edit the existing tree in place (and why not -) ...:

 tree = etree.parse('addressbook.xml') root = tree.getroot() NewSub = etree.SubElement ( root, 'CREATE_NEW_SUB' ) tree.write ( 'addressbook1.xml' ) 

which fits in addressbook1.xml :

 <addressbook> <person> <name>Eric Idle</name> <phone type="fix">999-999-999</phone> <phone type="mobile">555-555-555</phone> <address> <street>12, spam road</street> <city>London</city> <zip>H4B 1X3</zip> </address> </person> <CREATE_NEW_SUB /></addressbook> 

(I hope this is the effect you are looking for ...?)

+16
source share

All Articles