ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

NetBeans: Working with XML, Part 3
Pages: 1, 2, 3

Finally, we need to add logic to print the data for each element. This is easy in our example because only the Part element has data. Search the source for occurrences of the following commented line:

  // ((org.w3c.dom.Text)node).getData( );

Add the print statements shown in Table 11-3 right after the commented line that was found. Or replace the commented line with the new statement, if you prefer.

Table 11-3:

Printing element data in Inventory_InventoryScanner


Print statement


System.out.println(" Element Data: " + ((org.w3c.dom.Text)node).getData( ));

Now, configure execution parameters for the scanner, just as you did in the previous section for the parser. Open the Properties sheet for Inventory_InventoryScanner.java, click the Execution tab, and set the Arguments property to Inventory.xml. Invoke the Customizer dialog for the Executor property by clicking the value and then the ... button, click the Expert tab of the Customizer dialog to expose the Working Directory property, and set Working Directory to the directory that contains the Inventory.xml, the same as the source directory. It's time to test. Compile and execute Inventory_InventoryScanner. The results should match Example 11-8.

Next, add code to make a slight modification to the data values, just enough to prove that they're different when the new XML is output later. Locate the statements that you added to print the attribute values. Before each statement that you located, add a new statement to change the value of the data. We want to prove that the data was changed when it's output again later. Add statements that invoke attr.setValue as shown in Table 11-3. For example, to see what visitElement_Part looks like with all changes in place, see Table 11-4.

Table 11-4: Modifying attribute values in Inventory_InventoryScanner



Statement to modify data



attr.setValue("ID:" + attr.getValue( ));



attr.setValue("KD:" + attr.getValue( ));



attr.setValue("PD:" + attr.getValue( ));



attr.setValue("PC:" + attr.getValue( ));



attr.setValue("PS:" + attr.getValue( ));



attr.setValue("SD:" + attr.getValue( ));

Near the end of the visitElement_Part method locate the statement that prints the value of data in a Part node. Before the print statement add a statement invoking node.setData to change the text data, as shown in Example 11-10. The entire method is given to show all the added code in context.

Example 11-10: visitElement_Part method with all changes applied

/** Scan through org.w3c.dom.Element named Part. */
void visitElement_Part(org.w3c.dom.Element element) { // <Part>
   // element.getValue( );
   System.out.println("Element: Part");
   org.w3c.dom.NamedNodeMap attrs = element.getAttributes( );
   for (int i = 0; i < attrs.getLength( ); i++) {
      org.w3c.dom.Attr attr = (org.w3c.dom.Attr)attrs.item(i);
      if (attr.getName( ).equals("Description")) { // <Part Description="???">
         // attr.getValue( );
         attr.setValue("PD:" + attr.getValue( ));
         System.out.println(" Attribute: Description = " + attr.getValue( ));
      if (attr.getName( ).equals("Color")) { // <Part Color="???">
         // attr.getValue( );
         attr.setValue("PC:" + attr.getValue( ));
         System.out.println(" Attribute: Color = " + attr.getValue( ));
      if (attr.getName( ).equals("Size")) { // <Part Size="???">
         // attr.getValue( );
         attr.setValue("PS:" + attr.getValue( ));
         System.out.println(" Attribute: Size = " + attr.getValue( ));
   org.w3c.dom.NodeList nodes = element.getChildNodes( );
   for (int i = 0; i < nodes.getLength( ); i++) {
      org.w3c.dom.Node node = nodes.item(i);
      switch (node.getNodeType( )) {
         case org.w3c.dom.Node.CDATA_SECTION_NODE:
            // ((org.w3c.dom.CDATASection)node).getData( );
         case org.w3c.dom.Node.ELEMENT_NODE:
            org.w3c.dom.Element nodeElement = (org.w3c.dom.Element)node;
            if (nodeElement.getTagName( ).equals("Inventory")) {
            if (nodeElement.getTagName( ).equals("Kit")) {
            if (nodeElement.getTagName( ).equals("Part")) {
            if (nodeElement.getTagName( ).equals("Supplier")) {
         case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
            // ((org.w3c.dom.ProcessingInstruction)node).getTarget( );
            // ((org.w3c.dom.ProcessingInstruction)node).getData( );
         case org.w3c.dom.Node.TEXT_NODE:
            // ((org.w3c.dom.Text)node).getData( );
            ((org.w3c.dom.Text)node).setData("PT:" +
                     ((org.w3c.dom.Text)node).getData( ));
            System.out.println("  Element Data: " +
                     ((org.w3c.dom.Text)node).getData( ));

We're almost done. Let's take a moment to compile and test. The new output should show our modifications to the input data.

Finally, we'll add more code to output the modified XML data. We will use a Transformer object to copy the document with its modified data to an output stream. Add code to the main method so that it matches Example 11-11.

Example 11-11: main method with all changes applied

public static void main(String[ ] args) throws Exception {
   javax.xml.parsers.DocumentBuilderFactory builderFactory =
      javax.xml.parsers.DocumentBuilderFactory.newInstance( );
   javax.xml.parsers.DocumentBuilder builder =
      builderFactory.newDocumentBuilder( );
   org.w3c.dom.Document document =
      builder.parse (new org.xml.sax.InputSource (args[0]));
   Inventory_InventoryScanner scanner =
      new Inventory_InventoryScanner (document);
   scanner.visitDocument( );
   // Output modified Inventory.xml
   TransformerFactory tranFact = TransformerFactory.newInstance( );
   Transformer tran = tranFact.newTransformer( );
   DOMSource DSource = new DOMSource(document);
   StreamResult SResult = new StreamResult(System.out);
   tran.transform(DSource, SResult);

Add the import statements in Example 11-12 after the package statement at the top.

Example 11-12: Import statements for Transformer references

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

Compile and execute. Your output window should match Example 11-13 (except for a couple of line breaks added for readability). At the top is the data extracted and then modified from the input XML document. Next is the new XML document showing the modified data.

Example 11-13: Output from Inventory_InventoryScanner

Element: Inventory
   Attribute: Description = ID:Kit Inventory
Element: Kit
   Attribute: Description = KD:The first kit
Element: Part
   Attribute: Description = PD:Part A
   Element Data: PT:Part A in Kit
Element: Supplier
   Attribute: Description = SD:Our favorite supplier
Element: Part
   Attribute: Description = PD:Part A
   Element Data: PT:Part A in Supplier
Element: Part
   Attribute: Description = PD:Part A
   Attribute: Size = PS:Just right
   Attribute: Color = PC:Purple
   Element Data: PT:Part A alone

<!-- Created by vaughn on May 11, 2002, 9:01 PM -->
<Inventory Description="ID:Kit Inventory">
   <Kit Description="KD:The first kit">
      <Part Description="PD:Part A">PT:Part A in Kit</Part>

   <Supplier Description="SD:Our favorite supplier">
      <Part Description="PD:Part A">PT:Part A in Supplier</Part></Supplier>
   <Part Description="PD:Part A" Size="PS:Just right"
                 Color="PC:Purple">PT:Part A alone</Part>

These examples give the basics of reading, modifying, and writing XML documents with Java classes. NetBeans makes it easy to access XML documents wherever you find them or to generate your own whenever you need to share data with other applications. Just remember to use a SAX document handler if serial read access is adequate, especially when speed and memory are critical. Use a DOM tree scanner if you need random access to the data elements in the XML document, if you need to update the data, or if you need to generate a new document. SAX document handlers are widely used in web applications, where resources are tight. Keep that in mind while you're reading the next chapter.

Return to ONJava.com.