Creating and Parsing XML Documents in JDeveloper : Page 3

Creating an XML Document (continued)
To create any XML document, you first create an XML declaration by setting the XML version and the document encoding for output:

xmlDocument.setVersion("1.0");
xmlDocument.setEncoding("UTF-8");

Then you create the remainder of the document nodes in sequence, creating each element and adding each element, starting with the root node. In this case, for example, create the root element using the createElement(String) method. Cast the Element object returned by createElement() method to XMLElement:

The process to add the other elements and text nodes in the example XML document in Listing 1 is similar, so I won't list it exhaustively here. The XMLDocument class provides additional methods to create XML document elements other than those discussed in this section, so I've listed some of them in Table 3.

Figure 4. Running the Application. Right click on the CreateXMLDocument.java item in JDeveloper and select Run from the popup menu.

Write the XML document to the output stream using the printDocument(XMLDocument) method.

xmlPrintDriver.printDocument(xmlDocument);

XMLPrintDriver can print not only an XMLDocument node, but other nodes as well. Table 4 lists additional print methods in the XMLPrintDriver class that you may find useful.

You can see the complete listing for the CreateXMLDocument.java in Listing 2.

To run the completed CreateXMLDocument.java application in JDeveloper, right click on CreateXMLDocument.java in the Applications Navigator and select "Run" (see Figure 4). The application should generate the XML document.