Creating an XML Document with DOM


DocumentBuilderFactory fact =    DocumentBuilderFactory.newInstance( ); DocumentBuilder builder =    fact.newDocumentBuilder( ); Document doc = builder.newDocument( ); Element location = doc.createElement("Location"); doc.appendChild(location); Element address = doc.createElement("Address"); location.appendChild(address); Element city = doc.createElement("City"); address.appendChild(city); line.appendChild(doc.createTextNode("Flat Rock")); Element state = doc.createElement("State"); address.appendChild(state); state.appendChild(doc.createTextNode("Michigan")); ((org.apache.crimson.tree.XmlDocument)doc).       write(System.out);



In this phrase, we use the DOM API and JAXP to create an XML document. The XML segment created in this phrase is the following:

<Location>   <Address>     <City>Flat Rock</City>     <State>Michigan</State>   </Address> </Location>


The main class we use here is the org.w3c.dom.Document class. This class represents the DOM of an XML document. We create an instance of the Document class using a DocumentBuilder obtained from a DocumentBuilderFactory. Each element of an XML document is represented in the DOM as an Element instance. In the XML document we are creating, we have build Location, Address, City, and State as Element object. We append the root level element, the Location, to the document object using the Document object's appendChild() method. The Element class also contains an appendChild() method that we use to build the hierarchy of the document beneath the root element.

It is also relatively simple to create an Element with attributes using the DOM API. For example, to add an attribute of "id" with a value of "home" to the Location element, we would use the following code:

location.setAttribute("id","home");


In this phrase, the underlying DOM parser used is the Crimson parser. In the phrase, this implementation shows up in the final line, also shown below.

((org.apache.crimson.tree.XmlDocument)doc).       write(System.out);


JAXP is designed to support pluggable parser implementations, and thus if you find a parser that you prefer over the Crimson parser, you can still use that with the code contained in this phrase. You do have to make sure that whatever parser implementation you are using is included on your class path.

An alternative to using the JAXP API for working with XML is the JDOM API. JDOM is an open source project that is being standardized through the Java Community Process (JCP), under JSR 102. See http://www.jdom.org for more information about the JDOM API. JDOM provides a native Java API instead of the standard DOM API for reading and creating XML documents. Many find that JDOM is easier to use when creating XML documents than the DOM API.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net