XML Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.00

XML DOM Node Tree Example

This section provides a tutorial example on how to print out the DOM Node tree by DOMBrowser.java with a given XML file.

Now let's use another XML file, user.xml, with more elements to show the XML DOM Node tree structure:

<?xml version="1.0"?>
<user status="active">
 <!-- This is not a real user. -->
 <first_name>John</first_name>
 <last_name>Smith</last_name>
</user>

Run DOMBrowser.java with this XML file, you will get:

C:\herong\xml>java XMLBrowser user.xml

#document: 9, 1, -1, null
 user: 1, 9, 1, null
  |-status: 2, 1, -1, active
  #text: 3, 0, -1,

  #comment: 8, 0, -1,  This is not a real
  #text: 3, 0, -1,

  first_name: 1, 1, 0, null
   #text: 3, 0, -1, John
  #text: 3, 0, -1,

  last_name: 1, 1, 0, null
   #text: 3, 0, -1, Smith
  #text: 3, 0, -1,

  address: 1, 5, 0, null
   #text: 3, 0, -1,

   street: 1, 1, 0, null
    #text: 3, 0, -1, 1234 Main Road
   #text: 3, 0, -1,

   city: 1, 1, 0, null
    #text: 3, 0, -1, Bellville
   #text: 3, 0, -1,

  #text: 3, 0, -1,

The output is more interesting:

  • Line breaks are also parsed into "#text" nodes. This is why node "user" has 9 child nodes: 5 line breaks, 1 comment, and 3 elements: "first_name", "last_name" and "address".
  • For a node that represents an attribute of element, the node value is the attribute value. See node "status" under "user".

Notes and sample codes in this section are based on JDK 1.4.1_01.

Sections in This Chapter

What Is DOM (Document Object Model)?

Using DOM Implementation Provided in JDK 1.4

DOM Specifications and DOM Node Interface

DOMBrowser.java - DOM Interface Java Example

XML DOM Node Tree Example

Building a New DOM Document Object

Converting DOM Document Objects to XML Files

Dr. Herong Yang, updated in 2009
XML DOM Node Tree Example