Home > Articles

This chapter is from the book

This chapter is from the book

The DOM Structure

Now that we've gotten the lay of the land, it's time to actually do some programming.

Here we hit a crossroads. Nowhere in the preceding discussion do you see any mention of a programming language. In fact, eliminating language dependence is one of the major benefits of XML.

So how do we decide what language to use? Simple. We don't. I'm going to show you all the examples in Java, but I'm also going to provide some examples in languages such as C++ and Visual Basic .NET just to get you started. Once we're on the road, you can adapt the changes we make to the Java application to your own language. (This shows the advantage of a common API.)

In the last chapter, we looked at planning an application for increasing guest participation in activities at our outer space tourist resort. In this chapter, we're going to write a small portion of that application, and look at displaying the activities and taking reservations.

Getting Ready

Before you can build any DOM application, you'll need to have an implementation of the Document Object Model installed and ready to go. For the main examples, I'll be using the Java API for XML, or JAXP 1.2. Here are some other implementations:

Platform

DOM Implementation(s)

Java

JAXP, Apache Xerces-Java

C++

Microsoft Visual C++ .NET—COM and MSXML 4.0

Visual Basic

Microsoft Visual Basic .NET—MSXML 4.0

Perl

Apache Xerces, with XML::Xerces for DOM 2.0 support (XML::DOM supports only DOM 1.0, and won't work with the complete sample application, but is fine for general use.)

PHP

PHP 4.2.1 or later, compiled with DOM XML support (requires Gnome libxml2)


Make sure your software is installed and tested.

MSXML SDK

The MSXML SDK is undergoing many changes that will enable it to provide support for the various XML standards. SDK version 4.0 (the current release at the time of this writing) is required for the samples in this book. You can download the latest release of the SDK from the http://www.microsoft.com Web site in the Downloads area.

The Source Document

The application in this chapter is based on the document that we developed in the last chapter, which describes activities, people, and locations. The relevant portions of this document are shown in Listing 3.1.

Listing 3.1 The Source Document

<?xml version="1.0"?>
<activitysystem>
  <activities>
    <activity activityid="A1">
      <name>Zero-G Volleyball</name>
      <description>
        Even better than beach volleyball!
      </description>
      <date>4.30.45</date>
      <type>Sports</type>
      <limit>18</limit>
      <locationRef locationid="L1"/>
      <persons>
        <person personid="P2"/>
        <person personid="P1"/>
      </persons>
    </activity>
    <activity activityid="A2">
      <name>Stargazing</name>
      <description>
        Learn the visible constellations.
      </description>
      <date>4.29.45</date>
      <type>Educational</type>
      <limit>5</limit>
      <locationRef locationid="L1"/>
      <persons></persons>
    </activity>
  </activities>
  <maintenance>
...
    <locations>
      <location locationid="L1">
        <name>Zero-G Sports Arena</name>
        <deck>25</deck>
        <status>Closed</status>
        <equipment>
...
        </equipment>
        <equipment>
...
        </equipment>
      </location>
    </locations>
  </maintenance>
  <advertising>
...
  </advertising>
  <persons>
...
  </persons>
</activitysystem>

Parsing the Document

Before we can actually do anything with this data, we will need to parse it, or analyze it to determine the actual structure and content of the data. How we actually go about this will vary by implementation, because actually loading the document is one area where the specifics are not included in the DOM Level 2.0 Recommendation. Even within a single implementation, you may have several options for parsing a file to create a DOM document.

In this section, we'll look at how a number of different implementations go about creating a DOM document from an XML file.

Java

The JAXP implementation makes use of a DocumentBuilder to create the document, and a DocumentBuilderFactory to create the DocumentBuilder. The entire process is shown in Listing 3.2a.

Listing Numbers

Whenever the same process is performed in several languages, the listings will share a common number, but will be given a letter designation (for example, Listing 3.2a for Java, Listing 3.2b for C++, and so on).

Listing 3.2a Parsing the Document Using Java

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import org.w3c.dom.Document;

public class ActivityListing {

  public static void main (String args[]) {


   File docFile = new File("activities.xml");
   Document doc = null;

   try {

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     doc = db.parse(docFile);

   } catch (Exception e) {
     System.out.print("Problem parsing the file.");
   }

 }
}

Here we start with the basic application. First, instantiate the DocumentBuilderFactory using the static newInstance() method. Once it's created, the DocumentBuilderFactory creates the DocumentBuilder object using the newDocumentBuilder() method. The DocumentBuilder itself then parses the file, which you specified earlier. Compile and execute the application to check for errors.

Remember, the only part of this process that is part of the DOM Recommendation is the actual Document object. Let's look at the other implementations in the following sections.

C++

Listing 3.2b shows the same functionality as Listing 3.2a, but uses Microsoft Visual C++ and COM instead of Java.

Listing 3.2b Parsing the Document Using C++

#include "stdafx.h"
#import "C:\windows\system32\msxml2.dll"
using namespace MSXML2;

int _tmain(int argc, _TCHAR* argv[])
{
  ::CoInitialize(NULL);
  try
  {
    HRESULT hr;

    CComPtr<MSXML2::IXMLDOMDocument> pDomDocument;
    hr = pDomDocument.CoCreateInstance(__uuidof(MSXML2::DOMDocument));
    hr = pDomDocument->load("activities.xml");

  }
  catch(...)
  {
    wprintf(L"Caught the exception");
  }
  ::CoUninitialize();
  return 0;
}

In this example, msxml.dll is in the system32 directory of the Windows installation. Change the path to match your configuration. I modified the stdafx.h file so that I can use COM, so it now looks like this:

#define WIN32_LEAN_AND_MEAN
#define _WIN32_DCOM
#include <stdio.h>
#include <tchar.h>
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS

#include <windows.h>
#include <comdef.h>
#include <atlbase.h>

To get started, create a Win32 project and modify the Application Settings tab so the application type is Console Application. Select the ATL Support check box.

Visual Basic .NET

In Visual Basic, Microsoft's MSXML uses DOMDocument to load the file and parse it. To get started, create a new Windows Application project in VB and draw a pushbutton in the default form. From the Project menu, select Add Reference, and select Microsoft XML, v4.0 as the available reference. Then, in the click event of the pushbutton, we can add the code shown in Listing 3.2c.

Listing 3.2c Pushbutton Code Using VB

Private Sub Button1_Click(ByVal sender As System.Object,
             ByVal e As System.EventArgs) _
             Handles Button1.Click
  Dim xmldoc As New MSXML2.DOMDocument40()
  xmldoc.async = False
  xmldoc.load("activities.xml")
End Sub

We have created a new DOMDocument using the namespace MSXML2.

PHP

PHP's DOM support is very much in flux. The examples in this chapter use the new functions introduced in version 4.2.1, which for the most part are closer to DOM compliance than previous versions. However, as of version 4.2.1, PHP's DOM support is still incomplete, and function names (and functionality) may change in later versions. If you have a later or earlier version and the examples in this chapter don't work, check the DOM XML section of the PHP manual (listed in Appendix A, "Resources") for more information.

Listing 3.2d uses PHP to parse the activities.xml file.

Listing 3.2d Parsing the Document Using PHP

<?php

$file = "activities.xml";
if (!$doc = domxml_open_file($file)) {
 trigger_error("Failed to open or parse XML file '$file'", E_USER_ERROR);
}

?>

Perl

Perl file loading and parsing are done through the XML::Xerces::DOMParser interface. First create an input source from the target file, and then instantiate a parser. Use that parser to parse the file, and then retrieve the Document, as in Listing 3.2e.

Listing 3.2e Executing the Document Using Perl

use XML::Xerces;
use XML::Xerces::DOMParse;

my $file  = XML::Xerces::LocalFileInputSource->new("activities.xml");
my $parser = XML::Xerces::DOMParser->new();
eval { $parser->parse($file); };
XML::Xerces::error($@) if $@;

my $doc = $parser->getDocument();

XML::DOM

In case you don't have access to or can't install the Apache Xerces library and XML::Xerces, there is an alternative DOM implementation for Perl, called XML::DOM. XML::DOM is based on the expat parser, which is included with many Linux distributions, so Linux users may find it much easier to install than XML::Xerces. However, XML::DOM supports only DOM level 1.0; the full application described in this chapter will not work with XML::DOM.

That caveat aside, XML::DOM presents a DOM interface almost indistinguishable from XML::Xerces (as long as you only use DOM 1.0 features).

To parse the file with XML::DOM, use the following:

use XML::DOM;

my $parser = new XML::DOM::Parser;
my $doc  = $parser->parsefile("activities.xml");

Checking for Supported Features

With all of these differences, how do you know whether your implementation can do what you want it to? The answer is the DOMImplementation object. Implementations typically provide a nonstandard way to create a DOMImplementation without a Document object, but DOM also specifies that we can obtain a DOMImplementation from the Document itself, either as an object property or through a method.

Once you have the DOMImplementation, you can use it to test for specific modules. For example, our implementations should all support the DOM Level 2.0 Core module, but unless this book has been around for a while, they won't support Level 5.0. Listings 3.3a–e demonstrate the use of the DOMImplementation object.

Java

Listing 3.3a Checking for Support

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;

public class ActivityListing {

  public static void main (String args[]) {
   File docFile = new File("activities.xml");

   Document doc = null;
   try {

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     doc = db.parse(docFile);

     DOMImplementation domImpl = doc.getImplementation();
     if (domImpl.hasFeature("Core", "2.0")) {
      System.out.println("2.0 is supported.");
     } else {
      System.out.println("2.0 is not supported.");
     }

     if (domImpl.hasFeature("Core", "5.0")) {
      System.out.println("5.0 is supported.");
     } else {
      System.out.println("5.0 is not supported.");
     }

   } catch (Exception e) {
     System.out.print("Problem parsing the file.");
   }

 }

}

Executing and running the program should provide the following output:

2.0 is supported.
5.0 is not supported.

C++

Listing 3.3b shows the earlier C++ example extended to show the supported features.

Listing 3.3b Checking for Support with C++

#include "stdafx.h"
#import "C:\windows\system32\msxml2.dll"
using namespace MSXML2;

int _tmain(int argc, _TCHAR* argv[])
{
  ::CoInitialize(NULL);
  try
  {
    HRESULT hr;
    CComPtr<MSXML2::IXMLDOMDocument> pDomDocument;
    CComPtr<MSXML2::IXMLDOMImplementation> pDomImpl;

    hr = pDomDocument.CoCreateInstance(__uuidof(MSXML2::DOMDocument));
    hr = pDomDocument->load("activities.xml");
    hr = pDomDocument->get_implementation(&pDomImpl);

    if (SUCCEEDED(hr) && pDomImpl)
    {
      VARIANT_BOOL vtHasFeature = VARIANT_FALSE;
      vtHasFeature = pDomImpl->hasFeature(_bstr_t("MS-DOM"),
                        _bstr_t("2.0") );
      if (vtHasFeature == VARIANT_TRUE)
        wprintf(L"2.0 is supported\n");
      else
        wprintf(L"2.0 is not supported\n");
      vtHasFeature = VARIANT_FALSE;
      vtHasFeature = pDomImpl->hasFeature(_bstr_t("MS-DOM"),
                        _bstr_t("5.0") );
      if ( vtHasFeature == VARIANT_TRUE )
        wprintf(L"5.0 is supported\n");
      else
        wprintf(L"5.0 is not supported\n");
     }
  }

  catch(...)
  {
    wprintf(L"Caught the exception");
  }
  ::CoUninitialize();

return 0;

}

For MSXML, which is the Microsoft implementation of DOM standards, the supported feature is MS-DOM instead of Core.

Visual Basic

We can perform the same exercise in Visual Basic, as shown in Listing 3.3c. We'll extend the previous VB application to examine the supported features.

Listing 3.3c Checking for Support with VB

  Private Sub Button1_Click(ByVal sender As System.Object,
               ByVal e As System.EventArgs) _
               Handles Button1.Click
    Dim xmldoc As New MSXML2.DOMDocument40()
    xmldoc.async = False
    xmldoc.load("activities.xml")
    Dim objXMLDOMImpl As MSXML2.IXMLDOMImplementation
    objXMLDOMImpl = xmldoc.implementation
    If objXMLDOMImpl.hasFeature("MS-DOM", "2.0") Then
      MsgBox("2.0 is supported")
    Else
      MsgBox("2.0 is not supported")
    End If
    If objXMLDOMImpl.hasFeature("MS-DOM", "5.0") Then
      MsgBox("5.0 is supported")
    Else
      MsgBox("5.0 is not supported")
    End If
  End Sub

PHP

PHP supports most core DOM 2.0 functions, though with a nonstandard naming convention (PHP DOM functions look_like_this, notLikeThis). One thing not supported is the hasFeature() function; as of the current stable version of PHP (4.2.1 at the time of this writing), there is no way to query the implementation to find supported features.

Perl

Here, the Perl interface using XML::Xerces is almost identical to Java's JAXP. Syntax differences aside, you'll find that to be the case most of the time when you're working within a document.

Listing 3.3d Checking for Support with Perl

use XML::Xerces;
use XML::Xerces::DOMParse;

my $file  = XML::Xerces::LocalFileInputSource->new("activities.xml");
my $parser = XML::Xerces::DOMParser->new();
eval { $parser->parse($file); };
XML::Xerces::error($@) if $@;

my $doc = $parser->getDocument();

my $impl = $doc->getImplementation();

print "2.0 is supported.\n"  if $impl->hasFeature( 'Core', '2.0' );
print "5.0 is supported.\n"  if $impl->hasFeature( 'Core', '5.0' );

You should see output like the following:

2.0 is supported.

Examining the Structure of the Document

Now let's start looking at the actual document. Earlier we talked about the fact that elements and text are different types of nodes, with text nodes being the children of their element parents. Before we start building the application, let's take a look at how that shakes out in the actual document. In Listings 3.4a–e, we'll look at the names and values of several nodes.

We're going to see two important concepts in action:

  • Elements exist independently of their content.

  • Nodes exist in a parent-child relationship.

Java

Listing 3.4a Element and Text Nodes

...
import org.w3c.dom.Element;
import org.w3c.dom.Node;


public class ActivityListing {

  public static void println(String arg) {
   System.out.println(arg);
  }

  public static void main (String args[]) {
   File docFile = new File("activities.xml");
   Document doc = null;
   try {
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     doc = db.parse(docFile);
   } catch (Exception e) {
     System.out.println("Problem parsing the file.");
   }

   println("Get the document element.");
   Element root = doc.getDocumentElement();
   println("--The name of the document root is "
                        +root.getNodeName());
   println("--The value of the document root is "+
                    "["+root.getNodeValue()+"]");

   println(" ");
   println("Get the first child of the root element.");
   Node firstChild = root.getFirstChild();
   println("--The name of the first child is "
                     +firstChild.getNodeName());
   println("--The value of the first child is "+
                 "["+firstChild.getNodeValue()+"]");

   println(" ");
   println("Get the second child of the root element.");
   Node secondChild = firstChild.getNextSibling();
   println("--The name of the second child is "
                     +secondChild.getNodeName());
   println("--The value of the second child is "+
                 "["+secondChild.getNodeValue()+"]");
 }
}

Conventions

Throughout this and future chapters, we'll be using the same applications over and over, with changes and additions. Sections marked in bold are new, and sections that haven't changed and aren't relevant to the current discussion have been replaced with an ellipsis (...).

Figure 3.2 shows the relevant portions of the XML document.

Figure3.2Figure 3.2 The relevant portions of the document.

Here's the output of this application:

Get the document element.
--The name of the document root is activitysystem
--The value of the document root is [null]

Get the first child of the root element.
--The name of the first child is #text
--The value of the first child is [
  ]

Get the second child of the root element.
--The name of the second child is activities
--The value of the second child is [null]

The first step is to retrieve the document element, also known as the root element. As expected, this is the activitysystem element, as we can see when we retrieve the name of the node. The value of the node, however, might be a little surprising. Notice that because root is an Element node, it has a name, but not a value. The value of an Element node is always null, whether or not it has any content. If it does have content, the content is represented by its child nodes.

Root Element Versus Document Root

Note that the root element and the document root are not the same thing. The document root is the root of the document itself, and is actually the parent of the root element. The choice of getDocumentElement() as the name of the method that retrieves the root element is unfortunate, but don't let it confuse you!

Next, retrieve the first of those child elements. It may not be what you expect. The first child is not the activities element, but rather the whitespace node that precedes the activities element. This node doesn't have a name, but it has a value (between the brackets).

The activities element is actually the second child, as you'll see if you retrieve the next sibling. Again, because activities is an Element node, we have a name, but a value of null.

Now let's look at how we'd do the same thing in other languages.

C++

Listing 3.4b shows the retrieval of nodes using C++.

Listing 3.4b Accessing Elements and Text Nodes in C++

...
  hr = pDomDocument->load("activities.xml");
  // now let us get the elements and the text nodes
  CComBSTR bstrNodeName;
  CComPtr<MSXML2::IXMLDOMElement> pDomElement;
  hr = pDomDocument->get_documentElement(&pDomElement);
  hr = pDomElement->get_nodeName(&bstrNodeName);
  wprintf(L"Get the document element.\n");
  wprintf(L"--The name of the document root is %s \n", bstrNodeName);
  _variant_t vtValue;
  pDomElement->get_nodeValue(&vtValue);
  if ( vtValue.vt == VT_NULL )
    wprintf(L"--The value of the document root is [null]\n\n");
  else
  {
    CComBSTR bstrValue(vtValue.bstrVal);
    wprintf(L"--The value of the document root is [%s]\n\n",
        bstrValue);
  }

  CComPtr<MSXML2::IXMLDOMNode> pFirstChild;
  pDomElement->get_firstChild(&pFirstChild);
  if (pFirstChild)
  {
    CComBSTR bstrFirstChildNodeName;
    pFirstChild->get_nodeName(&bstrFirstChildNodeName);
    wprintf(L"Get the first child of the root element.\n");
    wprintf(L"--The name of the first child is %s \n",
        bstrFirstChildNodeName);
    _variant_t vtFirstChildValue;
    pFirstChild->get_nodeValue(&vtFirstChildValue);
    if (vtFirstChildValue.vt == VT_NULL)
      wprintf(L"--The value of the first child is [null]\n\n");
    else
    {
      CComBSTR bstrFirstChildValue(vtFirstChildValue.bstrVal);
      wprintf(L"--The value of the first child is [%s]\n\n",
          bstrFirstChildValue);
    }
    CComPtr<MSXML2::IXMLDOMNode> pSecondChild;
    pFirstChild->get_nextSibling(&pSecondChild);
    if (pSecondChild )
    {
      CComBSTR bstrSecChildNodeName;
      pSecondChild->get_nodeName(&bstrSecChildNodeName);
      wprintf(L"Get the second child of the root element.\n");
      wprintf(L"--The name of the second child is %s\n",
          bstrSecChildNodeName);
      _variant_t vtSecChildValue;
      pSecondChild->get_nodeValue(&vtSecChildValue);
      if (vtSecChildValue.vt == VT_NULL)
        wprintf(L"--The value of the second child is [null]\n\n");
      else
      {
        CComBSTR bstrSecChildValue(vtSecChildValue.bstrVal);
        wprintf(L"--The value of the second child is [%s]\n\n",
            bstrSecChildValue);
      }
    }
  }
...

Visual Basic

Listing 3.4c shows node access in Visual Basic.

Listing 3.4c Accessing Elements and Text Nodes in VB

...
    hr = xmldoc.load("activities.xml")
    Dim root As MSXML2.IXMLDOMElement
    root = xmldoc.documentElement
    Dim text As String
    text = "The name of the document root is "
    text = text & root.baseName
    MsgBox(text)

    Dim text2 As String
    text2 = "The value of the document root is "
    text2 = text2 & "[" & root.nodeValue & "]"
    MsgBox(text2)

    Dim firstchild As MSXML2.IXMLDOMNode
    firstchild = root.firstchild
    Dim firstchildname As String
    firstchildname = "The name of the first child is "
    firstchildname = firstchildname & firstchild.nodeName
    MsgBox(firstchildname)

    Dim firstchildvalue As String
    firstchildvalue = "The value of the first child is "
    firstchildvalue = firstchildvalue & "[" & firstchild.nodeValue & "]"
    MsgBox(firstchildvalue)

    Dim secondchild As MSXML2.IXMLDOMNode
    secondchild = firstchild.nextSibling
    Dim secondchildname As String
    secondchildname = "The name of the second child is "
    secondchildname = secondchildname & secondchild.nodeName
    MsgBox(secondchildname)

    Dim secondchildvalue As String
    secondchildvalue = "The value of the second child is "
    secondchildvalue = secondchildvalue &"["& secondchild.nodeValue & "]"
    MsgBox(secondchildvalue)
  End Sub

PHP

One thing to watch out for in the PHP implementation (see Listing 3.4d) is the non- standard naming of methods. Instead of the mixed-case style used in Java and Perl—where function names take the form getDocumentElement()—PHP generally uses underscores to separate individual "words" in method names, leading to methods with names like document_element(). You'll also notice that the PHP implementation of DOM drops the get from some functions, such as getDocumentElement() and getFirstChild(), but leaves it for others, such as getElementsByTagName(). In general, you'll probably have to check the PHP manual the first time you use a method to see how the name has been changed.

Listing 3.4d Accessing Elements and Text Nodes in PHP

<?php

$file = "activities.xml";
if (!$doc = domxml_open_file($file)) {
 trigger_error("Failed to open or parse XML file '$file'", E_USER_ERROR);
}

echo ("Get the document element.<br />");
$root = $doc->document_element();
echo ("--The name of the document root is " .
   $root->node_name() . "<br />");
echo ("--The value of the document root is [" .
   $root->node_value() . "]<br /><br />");

echo ("Get the first child of the root element.<br />");
$first_child = $root->first_child();
echo ("--The name of the first child is " .
   $first_child->node_name() . "<br />");
echo ("--The value of the first child is [" .
   $first_child->node_value() . "]<br /><br />");

echo ("Get the second child of the root element.<br />");
$second_child = $first_child->next_sibling();
echo ("--The name of the second child is " .
   $second_child->node_name() . "<br />");
echo ("--The value of the second child is [" .
   $second_child->node_value() . "]<br />");
?>

Perl

Listing 3.4e shows the Perl version.

Listing 3.4e Accessing Elements and Text Nodes in Perl

...
my $doc = $parser->getDocument();

print "Get the document element.\n";
my $root = $doc->getDocumentElement();
print "--The name of the document root is "
 . $root->getNodeName() . "\n";
print "--The value of the document root is ["
 . $root->getNodeValue() . "]\n\n";

print "Get the first child of the root element.\n";
my $first_child = $root->getFirstChild();
print "--The name of the first child is "
 . $first_child->getNodeName() . "\n";
print "--The value of the first child is ["
 . $first_child->getNodeValue() . "]\n\n";

print "Get the second child of the root element.\n";
my $second_child = $first_child->getNextSibling();
print "--The name of the second child is "
 . $second_child->getNodeName() . "\n";
print "--The value of the second child is ["
 . $second_child->getNodeValue() . "]\n";

Child Nodes, NodeLists, and Node Types

Before we get into the actual application, let's take one more look at the difference between element nodes and text nodes.

Every node has a type, which corresponds to one of the numeric constants defined within the Node interface. These constants are listed here:

ELEMENT_NODE          = 1
ATTRIBUTE_NODE         = 2
TEXT_NODE           = 3
CDATA_SECTION_NODE       = 4
ENTITY_REFERENCE_NODE     = 5
ENTITY_NODE          = 6
PROCESSING_INSTRUCTION_NODE  = 7
COMMENT_NODE          = 8
DOCUMENT_NODE         = 9
DOCUMENT_TYPE_NODE       = 10
DOCUMENT_FRAGMENT_NODE     = 11
NOTATION_NODE         = 12

This means that the value of getNodeType() for an element will be 1, the value for a text node will be 3, and so on. This allows us to compare the actual node type against the defined types in order to determine what sort of node we're dealing with.

In Listing 3.5, we'll retrieve a NodeList of all the children of the activitysystem element. DOM defines the NodeList interface, which contains an ordered list of objects. We'll then loop through the NodeList and examine the type for each node we find.

Listing 3.5 Examining Node Types

...
import org.w3c.dom.NodeList;

public class ActivityListing {
...
  public static void main (String args[]) {
...
   Element root = doc.getDocumentElement();
   NodeList children = root.getChildNodes();
   for (int i=0; i < children.getLength(); i++) {

      Node thisNode = children.item(i);
      if (thisNode.getNodeType() == thisNode.ELEMENT_NODE) {

       println("Element: "+thisNode.getNodeName());

      } else if (thisNode.getNodeType() == thisNode.TEXT_NODE) {

       println("Text: "+thisNode.getNodeValue());

      }
    }

   Node firstChild = root.getFirstChild();
   Node secondChild = firstChild.getNextSibling();
 }
}

If you're working in a language other than Java, you should be able to use what you've learned so far to adapt this code to your application.

The children NodeList holds all the child nodes of root, and for each one, compares the type against the standard types, outputting the appropriate content:

Text:

Element: activities
Text:

Element: maintenance
Text:

Element: advertising
Text:

Element: persons
Text:

Note that because there's no general else clause, nodes other than Text or Element won't show up at all.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020