|
Accessing different types of DOM tree nodes |
|
|
As it was already mentioned DOM-document contains the only root element.
The root in its turn consists of nodes. XML-element are concrete types of
those node. Except elements nodes can be also comments, text, attribute,
notation, processing instruction and event the document it self.
Since when we request a child from an element we get a node of unknown type,
we may use its getNodeValue() method to indicates its type and to cast
to corresponding interface:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
/**
* This sample program shows how to browse through DOM-tree,
* determine the types of DOM-nodes and printing their
* specific contents.
*/
public class Test {
public static void main(String[] args) {
try {
// first of all we request out
// DOM-implementation:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// then we have to create document-loader:
DocumentBuilder loader = factory.newDocumentBuilder();
// loading a document...
Document document = loader.parse("sample.xml");
// access to root element:
Element purchaseOrder = document.getDocumentElement();
// print a document element content:
printElement(purchaseOrder, "");
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static final void printElement(Element element, String indent) {
System.out.println("Element '" + element.getNodeName() + "'");
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
// recursive call for all element children:
printElement((Element) child, indent + "\t");
break;
case Node.ATTRIBUTE_NODE:
Attr attr = (Attr) child;
System.out.println("\tAttribute: '" +
attr.getName() + "' = '" + attr.getValue() + "'");
break;
case Node.COMMENT_NODE:
Comment comment = (Comment) child;
System.out.println("\tComment: '" + comment.getData() + "'");
break;
case Node.CDATA_SECTION_NODE:
CharacterData cdata = (CharacterData) child;
System.out.println("\tCDatat: '" + cdata.getData() + "'");
break;
case Node.TEXT_NODE:
Text text = (Text) child;
System.out.println("\tText: '" + text.getData() + "'");
break;
// ... all cases remaining ...
default:
System.out.println("\tUnknown node type: '"
+ child.getNodeType() + "'");
break;
}
}
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.