Libxml TxmlTextReader Tutorial

This tutorial is based on the Libxml2 TextReaderTutorial by Daniel Veillard, converted for BlitzMax by Bruce Henderson.

This tutorial will present the key points of this API, and some working examples to help you get started.


Table of Contents


Introduction : The API

In Libxml, the main API is tree based, where the parsing operation results in a document loaded completely in memory, and expose it as a tree of nodes all available at the same time. This is very simple and quite powerful, but has the major limitation that the size of the document that can be hamdled is limited by the size of the memory available. Libxml also provide a SAX based API, but that version was designed upon one of the early expat version of SAX, SAX is also not formally defined for C. SAX basically work by registering callbacks which are called directly by the parser as it progresses through the document streams. The problem is that this programming model is relatively complex, not well standardized, cannot provide validation directly, makes entity, namespace and base processing relatively hard.

The TxmlTextReader API acts as a cursor going forward on the document stream and stopping at each node in the way. The user's code keeps control of the progress and simply calls a Read() method repeatedly to progress to each node in sequence in document order. There is direct support for namespaces, xml:base, entity handling and adding DTD validation on top of it was relatively simple. This API is really close to the DOM Core specification. This provides a far more standard, easy to use and powerful API than the existing SAX. Moreover integrating extension features based on the tree seems relatively easy.

In a nutshell the TxmlTextReader API provides a simpler, more standard and more extensible interface to handle large documents than the existing SAX version.

Table of Contents


Walking a Simple Tree

Basically the TxmlTextReader API is a forward only tree walking interface. The basic steps are:

  1. Prepare a reader context operating on some input
  2. Run a loop iterating over all nodes in the document
  3. Free up the reader context

Here is a basic sample doing this:


Function processNode(reader:TxmlTextReader)
    ' handling of a node in the tree
End Function

Function streamFile:Int(filename:String)
    Local reader:TxmlTextReader
    Local ret:Int

    reader = TxmlTextReader.fromFile(filename)
    If reader <> Null Then
        ret = reader.read()
        While ret = 1
            processNode(reader)
            ret = reader.read()
        Wend
        reader.free()
        If ret <> 0 Then
            Print filename + " : failed to parse"
        End If
    Else
        Print "Unable to open " + filename
    End If
End Function

A few things to notice:

Table of Contents


Extracting Information for the Current Node

So far the example code did not indicate how information was extracted from the reader. It was abstrated as a call to the processNode() routine, with the reader as the argument. At each invocation, the parser is stopped on a given node and the reader can be used to query the node properties. Each Property is available as a function taking its name. Here follows a list of the properties and methods :

nodeType()

The node type:
1 - start element
15 - end of element
2 - attributes
3 - text nodes
4 - CData sections
5 - entity references
6 - entity declarations
7 - PIs
8 - comments
9 - the document nodes
10 - DTD/Doctype nodes
11 - document fragment
12 - notation nodes

name() the qualified name of the node, equal to (Prefix:)LocalName.
localName() the local name of the node.
prefix() a shorthand reference to the namespace associated with the node.
namespaceUri() the URI defining the namespace associated with the node.
baseUri() the base URI of the node. See the XML Base W3C specification.
depth() the depth of the node in the tree, starts at 0 for the root node.
hasAttributes() whether the node has attributes.
hasValue() whether the node can have a text value.
value() provides the text value of the node if present.
isDefault() whether an Attribute node was generated from the default value defined in the DTD or schema.
xmlLang() the xml:lang scope within which the node resides.
isEmptyElement() check if the current node is empty, this is a bit bizarre in the sense that <a/> will be considered empty while <a></a> will not.
attributeCount() provides the number of attributes of the current node.

Let's look first at a small example to get this in practice by redefining the processNode() function in the previous example:

Function processNode(reader)
	Print reader.depth() + " " + reader.nodeType() + " " + ..
		reader.name() + " " + reader.isEmptyElement()
End Function

and look at the result of calling streamFile("tst.xml") for various content of the XML test file.

For the minimal document "<doc/>" we get:

0 1 doc 1

Only one node is found, its depth is 0, type 1 indicate an element start, of name "doc" and it is empty. Trying now with "<doc></doc>" instead leads to:

0 1 doc 0
0 15 doc 0

The document root node is not flagged as empty anymore and both a start and an end of element are detected. The following document shows how character data are reported:

<doc><a/><b>some text</b>
<c/></doc>

We modifying the processNode() function to also report the node Value:

Function processNode(reader)
	Print reader.depth() + " " + reader.nodeType() + " " + ..
		reader.name() + " " + reader.isEmptyElement() + " " + ..
		reader.value()
End Function

The result of the test is:

0 1 doc 0 
1 1 a 1 
1 1 b 0 
2 3 #text 0 some text
1 15 b 0 
1 14 #text 0 

1 1 c 1 
0 15 doc 0  

There are a few things to note:

Table of Contents


Extracting Information for the Attributes

The previous examples don't indicate how attributes are processed. The simple test "<doc a="b"/>" provides the following result:

0 1 doc 1 

This proves that attribute nodes are not traversed by default. The hasAttributes property allow to detect their presence. To check their content the API has special instructions. Basically two kinds of operations are possible:

  1. to move the reader to the attribute nodes of the current element, in that case the cursor is positionned on the attribute node
  2. to directly query the element node for the attribute value

In both case the attribute can be designed either by its position in the list of attribute (moveToAttributeByIndex or getAttributeByIndex) or by their name (and namespace):

getAttributeByIndex(index) provides the value of the attribute with the specified index no relative to the containing element.
getAttribute(name) provides the value of the attribute with the specified qualified name.
getAttributeByNamespace(localName, namespaceURI) provides the value of the attribute with the specified local name and namespace URI.
moveToAttributeByIndex(no) moves the position of the current instance to the attribute with the specified index relative to the containing element.
moveToAttribute(name) moves the position of the current instance to the attribute with the specified qualified name.
moveToAttributeByNamespace(localName, namespaceURI) moves the position of the current instance to the attribute with the specified local name and namespace URI.
moveToFirstAttribute() moves the position of the current instance to the first attribute associated with the current node.
moveToNextAttribute() moves the position of the current instance to the next attribute associated with the current node.
moveToElement() moves the position of the current instance to the node that contains the current Attribute node.

After modifying the processNode() function to show attributes:

0 1 doc 1 
-- 1 2 (a) [b]

There are a couple of things to note on the attribute processing:

Table of Contents


Validating a Document

Also included in the API is the ability to DTD validate the parsed document progressively. This is simply the activation of the associated feature of the parser used by the reader structure. There are a few options available defined as follows:

Constant Description
XML_PARSER_LOADDTD force loading the DTD (without validating)
XML_PARSER_DEFAULTATTRS force attribute defaulting (this also imply loading the DTD)
XML_PARSER_VALIDATE activate DTD validation (this also imply loading the DTD)
XML_PARSER_SUBST_ENTITIES substitute entities on the fly, entity reference nodes are not generated and are replaced by their expanded content.

The getParserProp() and setParserProp() methods can then be used to get and set the values of those parser properties of the reader. For example

Function parseAndValidate(filename):
	Local reader:TxmlTextReader = TxmlTextReader.fromFile(filename)
	
	reader.setParserProp(PARSER_VALIDATE, 1)
	
	ret = reader.read()
	While ret = 1
		ret = reader.read()
	wend
	If ret <> 0 Then
		Print "Error parsing and validating " + filename
	End If
End Function

This routine will parse and validate the file.

Table of Contents


Entities Substitution

By default the TxmlTextReader will report entities as such and not replace them with their content. This default behaviour can however be overriden using:

reader.setParserProp(PARSER_SUBST_ENTITIES, 1)

Table of Contents


Relax-NG Validation

Libxml can also validate the document being read using the TxmlTextReader using Relax-NG schemas. While the Relax NG validator can't always work in a streamable mode, only subsets which cannot be reduced to regular expressions need to have their subtree expanded for validation. In practice it means that, unless the schemas for the top level element content is not expressable as a regexp, only a chunk of the document needs to be parsed while validating.

The steps to do so are:

Table of Contents


Mixing the Reader and Tree or XPath Operations

While the reader is a streaming interface, its underlying implementation is based on the DOM builder of libxml. As a result it is relatively simple to mix operations based on both models under some constraints. To do so the reader has an expand() operation allowing to grow the subtree under the current node. It returns a pointer to a standard node which can be manipulated in the usual ways. The node will get all its ancestors and the full subtree available. Usual operations like XPath queries can be used on that reduced view of the document.

Table of Contents