sashoalm
sashoalm

Reputation: 79447

Replace XML element with another element in Python

I need to replace a particular element from one XML file with another element from a different XML file. I get the element with XPath expressions and I don't have a handle to its parent.

What is the easiest way to in-place replace it so that if I write to a XML file it would reflect the change? I.e. I want to do what this pseudocode does:

# Pseudocode
tree1.open('input1.xml')
tree2.open('input2.xml')
element1 = tree1.findall(...)[0]
element2 = tree2.findall(...)[0]
element1.replaceWith(element2)
tree1.writeToXmlFile('merged.xml')

Upvotes: 0

Views: 130

Answers (1)

sashoalm
sashoalm

Reputation: 79447

Ok, I tried __setstate__ and __getstate__ and it worked:

element1.__setstate__(element2.__getstate__())

Upvotes: 2

Related Questions