Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an xml document in python

Tags:

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?

like image 397
mmattax Avatar asked Aug 27 '08 00:08

mmattax


People also ask

How do you create an XML file in Python?

Creating XML Document using Python First, we import minidom for using xml. dom . Then we create the root element and append it to the XML. After that creating a child product of parent namely Geeks for Geeks.

How do you create an XML document?

These are 3 ways to create a new XML File. Gather all of the content items you want to include in your XML file. Use Text Editor to create the XML data structure. Validate the XML data which you have created.

What is XML file in Python?

Extensible Markup Language, commonly known as XML is a language designed specifically to be easy to interpret by both humans and computers altogether. The language defines a set of rules used to encode a document in a specific format.


1 Answers

@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...

like image 80
mmattax Avatar answered Oct 22 '22 08:10

mmattax