2

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?

1 Answer 1

6

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.