bs7280
bs7280

Reputation: 1094

Add to an XML file in python

I would like to add to the end of an XML file using python.

The file is structured something like this:

<?xml version="1.0" ?>
<dic>
  <word-data>
    ...
  </word-data>
</dic>

And I would like to add another element in so that the file will look something like this:

<?xml version="1.0" ?>
<dic>
  <word-data>
    ...
  </word-data>
  <word-data>
    ...
  </word-data>
</dic>

Now for the programming Part!

What I am currently doing is "encoding" a list into xml using this function:

def make_xml(List):
    doc = Document();

    main = doc.createElement('dic')
    doc.appendChild(main)
    for l in List:
        parent = doc.createElement('word-data')
        main.appendChild(parent)

        for i in l:
            node = doc.createElement(i[0])
            node.appendChild(doc.createTextNode(str(i[1])))
            parent.appendChild(node)
    return doc

One of the lists looks like this:

List = [[['parent', 'node'],['parent', 'node'],['parent', 'node']]]

Now my question is how can I add this to the doc node in an existing XML file. I thought about turning the file into a list Then turning the doc into a new list, but I did not know how to do that, and I thought it may have been inefficient.

Anyways, any help is appreciated

Upvotes: 3

Views: 2831

Answers (1)

Matti Lyra
Matti Lyra

Reputation: 13088

If what you want to do is append to the xml file use one of Python's xml modules for instance for built-in xml.minidom http://docs.python.org/library/xml.dom.minidom.html

I am a little confused about the various loops in your sample code and the nested list structure but based on the output sample you procided I think what you want is something like:

from xml.dom.minidom import parse
def make_xml(filename, elements):
    dom = parse(filename)
    top_element = dom.documentElement

    for elmnt in elements:
        parent = doc.createElement('word-data')
        top_element.appendChild(parent)
        parent.appendChild(doc.createTextNode(elmnt))
    return dom



new_dom = add_to_xml_file('old_file.xml', ['foo','bar','baz'])

# save file
new_dom.writexml(open('new-bigger-file.xml','w'))

Upvotes: 3

Related Questions