The TreeBuilder API

Fredrik Lundh | August 2007

The TreeBuilder class takes a stream of start tag, end tag, and character data events, and builds an Element tree structure out of them. The event stream is represented as method calls to the builder object.

The builder is commonly used with the XMLParser class, but can be used by any kind of XML-like parser or other event source.

Example #

This example creates a builder instance, and adds a single element to it:

builder = ET.TreeBuilder()

builder.start("tag", {})
builder.data("some text")
builder.end("tag")

root = builder.close()

print ET.tostring(root)

This prints:

<tag>some text</tag>

The TreeBuilder Class #

builder = TreeBuilder()

Creates a tree builder instance.

Methods #

start #

start(tag, attrib) ⇒ element

Opens a new element, with the given tag and attributes (given as a dictionary).

This method returns the new element.

end #

end(tag) ⇒ element

Closes the current element.

The builder checks that the given tag matches the current element (as created by a matching call to start), and raises an assertion error if it doesn’t.

This method returns the closed element.

data #

data(text)

Adds text to the current element. The text should be either an 8-bit string containing ASCII text, or a Unicode string.

close #

close() ⇒ element

Flushes the builder buffers, and returns the root element.

The builder checks that the tree is correctly balanced (that is, that you’ve called end once for each call to start), and raises an assertion error if it isn’t.

 

A Django site. this page was rendered by a django application in 0.02s 2010-09-02 14:57:01.112136. hosted by webfaction.