Archive

Monthly Archives: February 2011

I found myself with the job of joining two XML documents. Should have been trivial but I don’t live and breathe XML so after false starts with XSLT and XInclude I tried with python.

Pretty straightforward, apart from finding some documentation for the libxml2 bindings.

 

# Take a bunch of XML files on the command line and merge them into
# one big XML document.
#
# The root element will come from the first document; the root elements of
# subsequent documents will be lost, as will anything outside the root
# (comments and whatnot).

import sys
import libxml2

doc = None
root = None

for i in range(1, len(sys.argv)):

    newdoc = libxml2.parseFile(sys.argv[i])
    newroot = newdoc.getRootElement()

    if newroot:
        if not root:
            # first document with a root element
            doc = newdoc
            root = newroot
        else:
            # merge this into previous document
            root.addChildList(newroot.children.copyNodeList())
            newdoc.freeDoc()

if doc:
    print doc
    doc.freeDoc()

%d bloggers like this: