XML technologies / XML / Python & XML / The Document Object Model / Extracting information
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
With DOM, extracting document information is easy. Most work lies in traversing the tree and selecting nodes relevant to the application. Then it is usually simple to call their methods or read their attributes. First, however, we need a DOM document object.
Creating a document object
Perhaps DOM’s greatest omission is an API for obtaining an object from an existing XML document. In browsers, documents finish loading before embedded or linked DOM scripts access them, so the environment places the object at a known location. Browserless applications need another solution.
That solution depends on the DOM implementation. We can create document objects from files, strings or URLs.
Loading a document with 4DOM
Creating a usable DOM instance in Python is easy. In 4DOM, one function loads an open file:
from xml.dom.ext.reader.Sax2 import FromXmlStream
doc = FromXmlStream(sys.stdin)Loading a document with minidom
The module xml.dom.minidom has two convenient loading functions. The function parse takes a filename or URL string, or an open readable file object:
import xml.dom.minidom
doc = xml.dom.minidom.parse(sys.stdin)Another function, parseString, loads XML text already buffered in memory:
doc = xml.dom.minidom.parseString("<doc>Mein kleines Dokument.</doc>") Determining node type
DOM constants identify the node type: element, attribute, CDATA section or many others. All constants are listed in The Python DOM API.
Compare the node’s nodeType attribute with the desired constant. A CDATASection instance has the value CDATA_SECTION_NODE for nodeType. An Element, possibly with children, has the value ELEMENT_NODE. While traversing the tree, test any node to see whether it is what you need:
for node in nodes.childNodes:
if node.nodeType == node.ELEMENT_NODE:
print "Gefunden!" The Node interface has other identifying properties, including a value and a name. The value of nodeName is the element tag name, whereas for a text node nodeName is simply #text. The nodeValue attribute can be empty for elements and normally holds character data for text or other leaf nodes.
Accessing children
DOM work mainly uses nodes and node lists. A node list collects nodes; every document level can be represented this way. Each node may itself contain more lists, allowing arbitrarily complex XML.
The Node interface provides two quick child-access methods and a way to obtain a list of all children. firstChild refers to the first child, or None if none. Knowing the exact document structure makes this useful. A strict content model enforced by a schema or DTD lets you rely on organization, provided validation is performed. Usually, however, follow XML’s spirit and traverse for the desired data rather than assume its location. In any case, firstChild is powerful and often retrieves the first element below the document element.
The lastChild attribute resembles firstChild but returns the last child. Useful when you know the structure or simply want the last child regardless of meaning.
The childNodes attribute holds all children as a node list and is widely used in DOM. When iterating through children, use childNodes like a list:
for child in node.childNodes:
print "Kind:", child.nodeName The value of childNodes is a NodeList object. For reading DOM data it behaves like a Python list, except it does not support slicing. NodeList objects should not modify DOM contents, since behavior depends on the implementation.
The NodeList interface has extra methods and attributes beyond lists, rarely used in Python but required by DOM. The attribute length returns the node count. This is the total length, with zero-based indexing: a NodeList of length 3 has indices 0, 1 and 2, like Python arrays. Most Python programmers prefer the built-in len, which works with NodeList objects.
The method item returns the item at its argument index. For example, item(1) returns the second node in the NodeList or None if fewer than two nodes exist. Python indexing differs: NodeList raises an IndexError for out-of-range indices.
Accessing siblings
XML documents are hierarchical and DOM represents them as trees, so accessing siblings as well as children is useful. Use the attributes previousSibling and nextSibling. The first child has previousSibling equal to None; the last child has nextSibling equal to None. An only child has both equal to None.
Combined with firstChild or lastChild, sibling attributes iterate through children. This takes more code but better supports tree modifications, especially adding or removing children during iteration.
Consider removing Directory elements from another Directory element to leave only files. Iterating through the top element’s childNodes and removing all Directory children skips some nodes. Python for loops use list indices, but removal shifts remaining children left, skipping one. Several solutions exist, perhaps simplest iterating with nextSibling:
child = node.firstChild
while child is not None:
next = child.nextSibling
if (child.nodeType == node.ELEMENT_NODE
and child.tagName == "Directory"):
node.removeChild(child)
child = nextExtracting elements by name
Depending on the task, DOM has advantages over SAX. No separate handler for every event type or event-grouping flags are needed, unlike the SAX example Improved ArticleHandler. Suppose a long XML purchase-order list must yield only part numbers for a report. With SAX, a handler looks for the part-number element, here sku, then sets a flag collecting character events until it ends. DOM instead offers getElementsByTagName on the document interface.
To show the simplification, create the following XML file, a sample purchase order for the next script:
<?xml version="1.0"?>
<purchaseOrder>
<item>
<name>Mushroom Lamp</name>
<sku>229-987488</sku>
<price>$34.99</price>
<qty>1</qty>
</item>
<item>
<name>Bass Drum</name>
<sku>228-988347</sku>
<price>$199.99</price>
<qty>1</qty>
</item>
<item>
<name>Toy Steam Engine</name>
<sku>221-388833</sku>
<price>$19.99</price>
<qty>1</qty>
</item>
</purchaseOrder> DOM easily creates lists referencing every node of one element type. For instance, collect all sku elements in a new list. Use it like any NodeList, except the nodes need not share a parent as in the childNodes example. Since DOM uses the structural tree, one call extracts a subset into a separate list. The next example uses getElementsByTagName to make one NodeList of all sku elements. Our example has text children under sku, but a string can span several DOM text nodes. Simplify the tree with normalize from the Node interface, merging adjacent text nodes into one. This makes the firstChild attribute of the Element class reliably supply the complete text of sku elements.
Example: po.py
#!/usr/bin/env python
from xml.dom.ext.reader.Sax2 import FromXmlStream
import sys
doc = FromXmlStream(sys.stdin)
for sku in doc.getElementsByTagName("sku"):
sku.normalize( )
print "Sku: " + sku.firstChild.dataThis uses considerably less code than an equivalent SAX handler, and extraction can run independently of other document work. Running again with po.xml produces output like:
Sku: 229-987488
Sku: 228-988347
Sku: 221-388833The example Improved ArticleHandler shows a comparable SAX approach.
Examining NodeList elements
Combine these ideas using article.xml from the preceding section, example article.xml. The next example recursively extracts text from document elements.
Example: textme.py
#!/usr/bin/env python
from xml.dom.ext.reader.Sax2 import FromXmlStream
import sys
def findTextNodes(nodeList):
for subnode in nodeList:
if subnode.nodeType == subnode.ELEMENT_NODE:
print "Element-Knoten: " + subnode.tagName
# Rufe Funktion erneut auf, um Kinder zu erhalten
findTextNodes(subnode.childNodes)
elif subnode.nodeType == subnode.TEXT_NODE:
print "Text-Knoten: ",
print subnode.data
doc = FromXmlStream(sys.stdin)
findTextNodes(doc.childNodes)Run it with article.xml as standard input:
$> python textme.py < article.xml Expected output resembles:
Element-Knoten: webArticle
Text-Knoten:
Element-Knoten: header
Text-Knoten:
Element-Knoten: body
Text-Knoten: Seattle, WA - Today an anonymous individual
announced that NASA has completed building a
Warp Drive and has parked a ship that uses
the drive in his back yard. This individual
claims that although he hasn't been contacted by
NASA concerning the parked space vessel, he assumes
that he will be launching it later this week to
mount an exhibition to the Andromeda Galaxy.
Text-Knoten:The output shows whitespace treated as separate text nodes and adjacent character strings kept together as text nodes. Your output may differ. Treat different parser versions or platforms as different parsers: interaction between buffering and the operating system matters. Exact text-node boundaries may therefore vary, and adjacent blocks of character data may span several nodes.
Examining attributes
After hierarchical content, consider XML’s nonhierarchical components: attributes. DOM represents them as nodes too, with a special relationship to the tree and different interfaces for access.
Earlier child traversal, as in textme.py, showed only element and text nodes. Attributes therefore are not children of their owning element. Access them through special Element methods. The Node interface has an attribute used only for element attributes.
The simplest value access is the element method getAttribute. It takes an attribute-name string and returns its value, or an empty string if absent. For the attribute node itself, use getAttributeNode, returning None if absent. To test existence without the node or value, use hasAttribute.
Another approach uses NamedNodeMap, a dictionary-like object sharing much of Python’s dictionary interface. The Node interface includes the attribute attributes, used only on elements; for other node types it is always None. Although NamedNodeMap, like NodeList, has the item method and length attribute, Python usually treats it as a mapping, supporting most dictionary operations. Keys are attribute names, values are attribute nodes.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de