XOM Tutorial
Elliotte Rusty Harold
Copyright © 2002-2008 Elliotte Rusty Harold
Table of Contents
Appending children
Serializer
Attributes
Document Type Declarations
Namespaces
Validating
Setting SAX Properties
Element Navigation
Siblings
Attributes
The Node Superclass
The ParentNode Class
Factories, Filters, Subclassing, and Streaming
XPath
XSLT
Canonicalization
XInclude
Summary
XOM is designed to be easy to learn and easy to use. It works very straight-forwardly, and has a very shallow learning curve. Assuming you're already familiar with XML, you should be able to get up and running with XOM very quickly.
Creating XML Documents
Let’s begin, as customary, with a Hello World program. In particular, suppose we want to create this XML document:
<?xml version="1.0"?> <root> Hello World! </root>
First we have to import the nu.xom package where most of the interesting classes live:
import nu.xom.*;
This document contains a single element, named root, so we create an Element object named “root”:
Element root = new Element("root");
Next we append the string "Hello World!" to it:
root.appendChild("Hello World!");
Now that we have the root element, we can use it to create the Document object:
Document doc = new Document(root);
We can create a String containing the XML for this Document object using its toXML method:
String result = doc.toXML();
This string can be written onto an OutputStream or a Writer in the usual way. Here’s the complete program:
Example 1. Hello World with XOM
import nu.xom.*;
public class HelloWorld {
public static void main(String[] args) {
Element root = new Element("root");
root.appendChild("Hello World!");
Document doc = new Document(root);
String result = doc.toXML();
System.out.println(result);
}
}
This is compiled and run in the usual way. When that’s done, here’s the output:
<?xml version="1.0"?> <root>Hello World!</root>
You may notice that this isn't quite what the goal was.
The white space is different. On reflection, this shouldn't be too surprising.
White space is significant in XML. If you want line breaks and indentation,
you should include that in the strings you use to construct the
data. For example,
root.appendChild("\n Hello World!\n");