caucho
 


This Example extracts and print the "b" node in the following XML.
Input XML
<top>
  <a/>
  <b>
    <b1/>
    <b2/>
  </b>
  <c/>
</top>

In XML, the document contains a single top element. We'll just extract that and store it.

Each DOM node has a name and a value retrieved using getNodeName() and getNodeValue(). For an Element, the name is the tag name and the value is null.

Traversing nodes uses a combination of:

  • getFirstChild()
  • getLastChild()
  • getNextSibling()
  • getPreviousSibling()
  • getParentNode()
Since those return a Node, you'll often need to cast the results to the correct type. Remember, that the child nodes also includes Text nodes, including whitespace-only text nodes. You can't assume that any child is an Element, So you'll always need to test the node name or the node type.

The following pattern is a common method for finding a node as the child.
Finding Elements with the DOM
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import com.caucho.xml.*;

...

// Create a new parser using the JAXP API (javax.xml.parsers)
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

// Create a new document
Document doc = builder.parse("test.xml");

// Get the top element
Element top = doc.getDocumentElement();

// Find the B element
Node ptr;
for (ptr = top.getFirstChild();
     ptr != null && ! ptr.getNodeName().equals("b");
     ptr = ptr.getNextSibling()) {
}


Copyright © 1998-2002 Caucho Technology, Inc. All rights reserved.
Resin® is a registered trademark, and HardCoretm and Quercustm are trademarks of Caucho Technology, Inc.