[XML-SIG] creating dom tree from node

paul.boddie at ementor.no paul.boddie at ementor.no
Thu Sep 18 07:28:19 EDT 2003


Steffen Higel [mailto:Steffen.Higel at cs.tcd.ie] wrote:
> 
> A newbie question here and google hasn't been too helpful.
> 
> I'm running an xpath query on an xml document, which works fine. I then 
> want to load the nodes that it returns into a dom tree to get the useful
> information out of them.

Well, the result of an XPath query is typically a list of qualifying nodes
which you can inspect individually using the DOM API.

> The problem is I can't  work out how to get from a Node to a doc. If I
> could even work out how to get the Node into a string, I could use the
> reader.fromString function to do this.

The creation of documents seems to be unstandardised between Python DOMs,
unless this has all changed recently. In xml.dom.minidom, the easiest way of
doing what you want is as follows:

# Set up an example.
s = "<doc><node>text</node></doc>"
from xml.dom.minidom import parseString
d = parseString(s)
import xml.xpath
l = xml.xpath.Evaluate("//node", d)

# Note that the contents of 'l' are DOM nodes anyway.
# Contentious way of creating a document.
d2 = xml.dom.minidom.Document()

# Import the first qualifying node into the new document (the 1 means that
# "deep copying" takes place).
n = d2.importNode(l[0], 1)

# Insert the copied node as the root node in the document.
# Note that some DOMs get upset about this because the document creation
# process actually creates a root node.
d2.appendChild(n)

Personally, I've written a small wrapper module to shield me from various
differences between DOMs, like that of document creation, for example. From
what I recall from a perusal of W3C documentation, I suppose
DocumentFragment objects are employed for copying between documents,
although I'm not too sure if that is what importNode returns when called.

Paul



More information about the XML-SIG mailing list