Java Tutorial - Java Script :
Processing XML with XOM
Attribute, LeafNode, and ParentNode. 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);
The appendChild() method appends a new child below all other children of that parent. The preceding statements produce this XML fragment:
<channel>
<link>http://www.cadenhead.org/workbench/</link>
</channel>
The appendChild() method also can be called with a String argument instead of a node. A Text object representing the string is created and added to the element:
link.appendChild(“http://www.cadenhead.org/workbench/”);
After a tree has been created and filled with nodes, it can be displayed by calling the Document method toXML(), which returns the complete and well-formed XML document as a String.
Listing 19.3 shows the complete application.
The RssStarter application displays the XML document it creates on standard output. The following command runs the application and redirects its output to a file called feed.rss:
java RssStarter > feed.rss
XOM automatically precedes a document with an XML declaration. The XML produced by this application contains no indentation; elements are stacked on the same line.
XOM only preserves significant whitespace when representing XML data—the spacesbetween elements in the RSS feed contained in Listing 19.2 are strictly for presentation purposes and are not produced automatically when XOM creates an XML document. A subsequent example demonstrates how to control indentation.
