3

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

1
  • 1
    Why was this downvoted? I can clearly understand what the OP wants to accomplish here. +1 to counteract it. Commented Aug 24, 2012 at 17:42

1 Answer 1

3

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'))
Sign up to request clarification or add additional context in comments.

3 Comments

If you also show a small example of how to fix the OPs make_xml to produce a new word-data node, instead of a whole new doc, so that it integrates with this good solution, I will upvote.
Cool. I am sure this will be very helpful to the OP to see how it all works together :-)
Worked beautifully, only had to change all occurances of "doc" to "dom"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.