Java Reference
In-Depth Information
This statement creates an object for the root element of the document,
rss
.
Element
's
one-argument constructor can be used because the document does not employ a feature
of XML called namespaces; if it did, a second argument would be necessary: the name-
space uniform resource identifier (URI) of the element. The other classes in the XOM
library support namespaces in a similar manner.
In the XML document in Listing 19.2, the
rss
element includes an attribute named
ver-
sion
with the value “2.0”. An attribute can be created by specifying its name and value
in consecutive arguments:
Attribute version = new Attribute(“version”, “2.0”);
Attributes are added to an element by calling its
addAttribute()
method with the
attribute as the only argument:
rss.addAttribute(version);
The text contained within an element is represented by the
Text
class, which is con-
structed by specifying the text as a
String
argument:
Text titleText = new Text(“Workbench”);
When composing an XML document, all of its elements end up inside a root element
that is used to create a
Document
object—a
Document
constructor is called with the root
element as an argument. In the
RssStarter
application, this element is called
rss
. Any
Element
object can be the root of a document:
Document doc = new Document(rss);
In XOM's tree structure, the classes representing an XML document and its constituent
parts are organized into a hierarchy below the generic superclass
nu.xom.Node
. This
class has three subclasses in the same package:
Attribute
,
LeafNode
, and
ParentNode
.
19
To add a child to a parent node, call the parent's
appendChild()
method with the node to
add as the only argument. The following code creates three elements—a parent called
domain
and two of its children,
name
and
dns
:
Element channel = new Element(“channel”);
Element link = new Element(“link”);
Text linkText = new Text(“http://www.cadenhead.org/workbench/”);
link.appendChild(linkText);
channel.appendChild(link);