20

Here is my sample code:

from xml.dom.minidom import *
def make_xml():
    doc = Document()
    node = doc.createElement('foo')
    node.innerText = 'bar'
    doc.appendChild(node)
    return doc
if __name__ == '__main__':
    make_xml().writexml(sys.stdout)

when I run the above code I get this:

<?xml version="1.0" ?>
<foo/>

I would like to get:

<?xml version="1.0" ?>
<foo>bar</foo>

I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?

2 Answers 2

13

@Daniel

Thanks for the reply, I also figured out how to do it with the minidom (I'm not sure of the difference between the ElementTree vs the minidom)


from xml.dom.minidom import *
def make_xml():
    doc = Document();
    node = doc.createElement('foo')
    node.appendChild(doc.createTextNode('bar'))
    doc.appendChild(node)
    return doc
if __name__ == '__main__':
    make_xml().writexml(sys.stdout)

I swear I tried this before posting my question...

Sign up to request clarification or add additional context in comments.

Comments

9

Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "node.noSuchAttr = 'bar'" would also not give an error).

Unless you need a specific feature of minidom, I would look at ElementTree:

import sys
from xml.etree.cElementTree import Element, ElementTree

def make_xml():
    node = Element('foo')
    node.text = 'bar'
    doc = ElementTree(node)
    return doc

if __name__ == '__main__':
    make_xml().write(sys.stdout)

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.