user130810
user130810

Reputation: 33

Copy and Write XML Node in Python

I've got a large XML file that I need to parse and look for a specific node. Once it has been found, I need to make a copy, edit a couple of values and write the file again.

So far I've managed to get the DOM element that I want. There is actually two of these elements already in the XML so after I'm finished, there will be three. Once I've made a copy of the DOM and edited the value, how do I then write this into the DOM (and thus the file)?

I'm using Python's from xml.dom import minidom at the moment.

Upvotes: 3

Views: 3949

Answers (2)

Edmon
Edmon

Reputation: 4872

In minidom you start with creating Document:

 Document doc = Document("your_root")

then if it is a text node you want to add, you append it with:

 text_node = doc.createTextNode(str(some content))
 doc.appendChild(text_node)

if you had for example <some_elem key="my value">some my text</some_elem>:

do it like this:

text_node = doc.createTextNode('some my text')
elem.appendChild(text_node)
elem.setAttribute('key', 'my value')

if it is complex element create it with:

elem = doc.createElement('your_elem')

if you need to set attributes do:

elem.setAttribute("some-attribute",your_attr)

if you need to append something to it:

elem.appendChild( some_other_elem )

then append the element:

doc.appendChild( elem )

if you need a string representation do:

doc.toxml()

of

doc.toprettyxml()

Upvotes: 4

Jakob S.
Jakob S.

Reputation: 1891

From the minidom documentation:

from xml.dom.minidom import getDOMImplementation

impl = getDOMImplementation()

newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')
top_element.appendChild(text)

So I guess appendChild is what you ask for?

Upvotes: 1

Related Questions