Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Lxml - Append a existing xml with new data

Tags:

python

xml

lxml

I am new to python/lxml After reading the lxml site and dive into python I could not find the solution to my n00b troubles. I have the below xml sample:

---------------
<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 append one child to the root element and write the entire file back out as a new xml or over write the existing xml. Currently all I am writing is 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

like image 217
Nathaniel Dickerson Avatar asked Sep 06 '10 02:09

Nathaniel Dickerson


People also ask

Is XML and lxml are same?

lxml is a reference to the XML toolkit in a pythonic way which is internally being bound with two specific libraries of C language, libxml2, and libxslt. lxml is unique in a way that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API.

What is tail in XML?

Elements contain text text and . tail are enough to represent any text content in an XML document.


1 Answers

You could make a new tree by copying over all of the old one (not just the root tag!-), but it's much simpler 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 puts 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>

(which I hope is the effect you're looking for...?-)

like image 52
Alex Martelli Avatar answered Sep 24 '22 07:09

Alex Martelli