Greg Symsym
Greg Symsym

Reputation: 101

Python:LXML - How to add an element to an existing element tree

I need to modify an existing xml file by adding a sub-element to an existing element. I use the lxml library.

<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>

here is the XML; let's ssuppose I want to add a second name:

<addressbook>
<person>
    <name>Eric Idle</name>
    <name>TEST TEST</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 know i can parse the file and get the root with etree.getroot() but can I get /adressbook/person as an etree.element?

Upvotes: 2

Views: 4048

Answers (1)

ewcz
ewcz

Reputation: 13087

you can use xpath to locale all the <name> elements of interest and then append a sibling element:

from lxml import etree

data = r'''
<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>
<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>
'''

doc = etree.fromstring(data)

#process the first <name> element of every person in addressbook
for name in doc.xpath('/addressbook/person/name[1]'):
    parent = name.getparent()
    parent.insert(parent.index(name)+1, etree.XML('<name>TEST TEST</name>'))

print(etree.tostring(doc))

Upvotes: 6

Related Questions