XML technologies / XML / Python & XML / The Document Object Model / Modifying documents

(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)

Having extracted information using DOM, we will probably want changes too. Only a few basics are required, so we explain them before examples: creating, adding, moving and removing nodes, and changing their contents. Since new elements and text are common needs, we start with creating nodes.

Creating nodes

New nodes normally require explicit creation. DOM defines interfaces, not concrete classes, so call methods on existing objects to create them. Fortunately, Document has many factory methods for most node types. Methods for Entity and Notation nodes are notably absent, though most applications should not suffer.

The commonest factories are simple: elements and text. Create elements using createElement with the tag name as its only argument. Create text with createTextNode, passing its content. For other factories, consult Python DOM API.

Adding and moving nodes

Convenient tree-movement methods belong to the base Node interface and are available to every node. Restrictions prevent structurally nonsensical documents, guaranteeing well-formedness. Adding children to text or a second child element to Document raises an exception, for example.

appendChild(newChild)

Takes a newChild node argument and appends it to the child list.

insertBefore(newChild, refChild)

Takes node newChild and inserts it immediately before refChild.

replaceChild(newChild, oldChild)

Replaces oldChild with newChild and returns oldChild to the caller.

removeChild(oldChild)

Removes node oldChild from the child list of the node on which the method is called.

These brief descriptions do not replace the reference; see Python DOM API for complete information.

Deleting nodes

Let us inspect a tree and remove nodes. The next example uses nested loops to descend three levels into XML generated by index.py from the example index.py. Assuming a maximum depth of three limits the design, but demonstrates the methods of interest.

Example: domit.py

#!/usr/bin/env python
import sys

from xml.dom.ext.reader.Sax2 import FromXmlStream
from xml.dom.ext import PrettyPrint

# Hole DOM-Objekt
doc = FromXmlStream(sys.stdin)

# Entferne unerwünschte Knoten durch Traversieren des Knotenbaums

for node1 in doc.childNodes:    
    for node2 in node1.childNodes:
        node3 = node2.firstChild
        while node3 is not None:
            next = node3.nextSibling
            name = node3.nodeName
            if name in ("contents", "extension", "userID", "groupID"):
              # Entferne unerwünschte Knoten hier mittels Elternelement
              node2.removeChild(node3)
            node3 = next

PrettyPrint(doc)

After reading standard input, nested for loops descend three levels looking for tag names. Run this on XML from index.py and the file elements should look like this:

<file name='c:\windows\desktop\G-Force\G-Force.doc'>

  <size>12570</size>
  <lastAccessed>Tue May 09 00:00:00 2000</lastAccessed>
  <lastModified>Tue May 09 11:56:14 2000</lastModified>
  <created>Wed Jan 17 23:31:23 2001</created>

</file>

Whitespace around removed elements remains, leaving gaps. Adjacent text nodes were not examined and remain unaffected. This output came from calling PrettyPrint at the script’s end. Elements look the same regardless of hierarchy position. Keep DOM code independent of structure: instead of using firstChild to find things, enumerate and inspect children. This may take longer but permits flexible structures and finds a target anywhere under its parent. Using firstChild can cause trouble with slightly different structures, such as a similar element inserted earlier. Use recursion to process structures regardless of position. If a node’s location within a subtree does not matter, the previously described method getElementsByTagName is available.

Another common need is a child of a known parent, without a fixed list position. A simple loop in a helper does this elegantly:

from xml.dom import Node

def findChildrenByTagName(parent, tagname):    
    """Liefert eine Liste von 'tagname'-Kindern von 'parent'."""
    L = []
    for child in parent.childNodes:
        if (child.nodeType == Node.ELEMENT_NODE
            and child.tagName == tagname):
          L.append(child)
    return L

An even simpler useful helper finds the first child with a given tag, or one of several tags. These are small variations of the preceding function.

Changing document structure

DOM can completely restructure a document, beyond replacements and additions.

Now replace the nested loops with recursion. This script also uses XML from index.py. This time, the size child of the file element replaces its parent. Afterwards, only directory and size elements remain.

This example shows domit2.py with recursion.

Example: domit2.py

#!/usr/bin/env python

from xml.dom.ext.reader.Sax2 import FromXmlStream
from xml.dom.ext              import PrettyPrint

import sys

def makeSize(nodeList):
   for subnode in nodeList:
      if subnode.nodeType == subnode.ELEMENT_NODE:
      if subnode.nodeName == "size":
         subnode.parentNode.parentNode.replaceChild(
           subnode, subnode.parentNode)
      else:
         makeSize(subnode.childNodes)

# Hole DOM-Objekt
doc = FromXmlStream(sys.stdin)

# Rufe Funktion auf
makeSize(doc.childNodes)

# Zeige verändertes Dokument an
PrettyPrint(doc)

Run it from the command line:

 $> python domit2.py < wd.xml 

The file wd.xml is XML generated by index.py, but any file with the same structure as output from index.py works. Output should resemble:

<Directory name='c:\windows\desktop\gl2'>
  <size>230444</size>
  <size>3035</size>
  <size>8904</size>
  <size>722</size>
  <Directory name='c:\windows\desktop\gl2/Debug'>
    <size>156672</size>
    <size>86016</size>
    <size>3779068</size>
    <size>25685</size>
    <size>17907</size>
    <size>250508</size>
    <size>208951</size>
    <size>402432</size>
  </Directory>
  <size>3509</size>
  <size>33792</size>
  <size>722</size>
  <size>48640</size>
  <size>533</size>
</Directory>

  

 

 

 

back to top