CS210 Tues., Apr. 18
Handout: DOM Node API (subset of JDK Javadoc)
Look at XML examples handed out last time (and in pa05 files directory)
Draw tree for slideshow example--all these are Nodes in the DOM tree.
The Node API is the crucial API for using the DOM tree set up for you by the code in main of DomEcho01.java.
The DOM parser reads the XML text file, builds a whole tree of nodes from it representing everything in the XML file.
We can then navigate around in the DOM tree, find out about the XML data.
We looked at the methods of Node, and the table that gives the nodeName, nodeValue, etc.
Navigating the DOM tree.
getChildNodes is crucial here: basic loop is
NodeList children = node.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Node child = children.item(i);
System.out.println(child);
}
Traversal in document order, i.e., preOrder of the tree.
It's like the filesystem traversal, pg. 603, where from a directory,
you obtain a list of all its files, including its subdirectories.
Then while listing those files, when you find a directory, you
recurse to list its files.
Here we list nodes, and if a node has children, recurse to report on them.
static void listAll(int depth, Node n)
{
printName(n, depth); // indent using level
NodeList children = n.getChildNodes();
for (int i=0; i<children.getLength(); i++) {
Node child = children.item(i);
listAll(depth+1, child);
}
}
No base case for recursion, but recursion does stop, because you get to
the bottom of the tree, where there are no more children, and the loop
has no passes.
.