Varun Verma
Varun Verma

Reputation: 295

lxml - unable to replace children of children

I'm using lxml as a solution for XML parsing in my application.

I understand that lxml can only replace the immediate child of a parent, but no levels under that child using .replace

Example XML:

<root>

    <dc>

        <batman alias='dark_knight' />

    </dc>

</root>

I have a modified tag in a string like so

<batman alias='not_dark_knight' />

I need some help with replacing the original XML using xpath '/root/dc/batman'.

from lxml import etree

original_xml = "<root><dc><batman alias='dark_knight' /></dc></root>"
modified_tag = "<batman alias='not_dark_knight' />"
x_path = '/root/dc/batman'
original_obj = etree.fromstring(original_xml)
modified_obj = etree.fromstring(modified_tag)

original_obj.replace(original_obj.xpath(x_path)[0], modified_obj)

This throws a ValueError: Element is not a child of this node. Is there a way i can replace the string nicely? (only using lxml)

Please understand that I would like a solution using lxml library only.

Upvotes: 3

Views: 1172

Answers (1)

alecxe
alecxe

Reputation: 473893

As you already know, you should be calling replace() on the parent of the element you want to replace. You may use .getparent() to dynamically get to the parent:

batman = original_obj.xpath(x_path)[0]
batman.getparent().replace(batman, modified_obj)

Upvotes: 3

Related Questions