How do I create a new Node using pulldom?

Paul Boddie paul at
Sat Jun 21 00:42:00 CEST 2008

On 20 Jun, 22:17, "susan_... at" <saqib.ali... at>
> I'm using xml.dom.pulldom to parse through an XML file. I use
> expandNode() to scrutinize certain blocks of it that I'm interested
> in.

Right. This is the thing which differentiates pulldom from traditional
DOM implementations, which I'll discuss below.

> Once I find a block of XML in the input file that I'm interested in, I
> need to add my own block <MyTag>.....</MyTag> to the pulldom tree I'm
> building in memory.


> The documentation on PullDom is worse than atrocious. It is simply non-
> existant. I can't even find a simple explanation of what the functions
> are named and what arguments they take. Sheesh.

Sheesh, indeed. I think the authors assumed a familiarity with the DOM
APIs, but they're regarded as being somewhat "old school" by many
these days, so it's possible that you aren't too familiar with the
PyXML/DOM style of the API employed.

> When I have a node N of the tree, I think that I can use
> N.appendChild() to do what I want (just guessing from the function
> name which I can see).
> appendChild takes 1 argument -- a new node.

Correct. I think that you also need to have expanded the part of the
document where the node will be placed. For example:

  stream = xml.dom.pulldom.parseString(s)
  for event, node in stream:
      if <some condition>:

> But I don't know how to create such a node.

This is a traditional DOM activity, but it's easy to be disoriented if
you don't already have a document object (which has the necessary
methods). However, such an object is readily available:

          doc = node.ownerDocument

You can then create a node using the usual create* methods. For

          element = doc.createElement("new")

And then you can use appendChild on the original node:


Note that since the document under node has been expanded, subsequent
nodes pulled from the stream will start with an END_ELEMENT event
involving the node concerned.

> Can someone out there please post a code fragment showing how to
> create a pulldom node? The simpler and more commented it is the
> better.

Try this:

  import xml.dom.pulldom
  s = "<test><node>xxx</node></test>"

  # Start parsing.
  stream = xml.dom.pulldom.parseString(s)

  # Process each event.
  for event, node in stream:

      # Do the addition of an element within "node".
      if event == xml.dom.pulldom.START_ELEMENT and \
          node.localName == "node":

          # Have to expand first.

          # Get the document and create the element.
          doc = node.ownerDocument
          element = doc.createElement("new")

          # Add the element; see what we've produced.
          print node.toxml()

Hope this helps!


More information about the Python-list mailing list