3

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.

2 Answers 2

4

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()
2
  • If I have an element of the form <FIELD ID="abc" TITLE="hello">VALUE</FIELD>. How do I set the VALUE once I have the element? Thanks for your help! :D
    – user130810
    Aug 3, 2012 at 11:59
  • Try doing a: field.childNodes[0].nodeValue = new_val. Catching any IndexErrors and the like.
    – Federer
    Aug 3, 2012 at 12:52
1

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?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.