The resulting object is an instance of XmlDocument. In case the document cannot be parsed, a ParserError is thrown.

To write back the parsed XML document simply call toString():

print(document.toString());

Traversing and Querying

Accessors allow to access nodes in the XML tree:

attributes returns an iterable over the attributes of the current node.

children returns an iterable over the children of the current node.

There are various methods to traverse the XML tree along its axes:

preceding returns an iterable over nodes preceding the opening tag of the current node in document order.

descendants returns an iterable over the descendants of the current node in document order. This includes the attributes of the current node, its children, the grandchildren, and so on.

following the nodes following the closing tag of the current node in document order.

ancestors returns an iterable over the ancestor nodes of the current node, that is the parent, the grandparent, and so on. Note that this is the only iterable that traverses nodes in reverse document order.

For example, the descendants iterator could be used to extract all textual contents from an XML tree:

Note the element method. It is quite sophisticated and supports many different optional named arguments:

The most common is the nest: argument which is used to insert contents into the element. In most cases this will be a function that calls more methods on the builder to define attributes, declare namespaces and add child elements. However, the argument can also be a string or an arbitrary Dart object that is converted to a string and added as a text node.

While attributes can be defined from within the element, for simplicity there is also an argument attributes: that takes a map to define simple name-value pairs.

Furthermore we can provide an URI as the namespace of the element using namespace: and declare new namespace prefixes using namespaces:. For details see the documentation of the method.

The builder pattern allows you to easily extract repeated parts into specific methods. In the example above, one could put the part that writes a book into a separate method as follows:

Supports

Limitations

Doesn't validate namespace declarations.

Doesn't validate schema declarations.

Doesn't parse and enforce DTD.

History

This library started as an example of the PetitParser library. To my own surprise various people started to use it to read XML files. In April 2014 I was asked to replace the original dart-xml library from John Evans.