recursively traversing an XML Element using DocumentTraversal in Java
I have been using the following code structure to traverse XML documents
and it works pretty well:
import org.w3c.dom.traversal.*;
...
private static SomeReturnType traverse(Document doc) {
DocumentTraversal dt = (DocumentTraversal) doc;
NodeIterator i = dt.createNodeIterator(doc, NodeFilter.SHOW_ELEMENT,
null, false);
Node node = i.nextNode();
while (node != null) {
// do stuff
node = i.nextNode();
}
return ...
}
However, how is it possible to generalize the above to allow traversal in
a random XML Element of the document, and not just the document as a
whole? This should theoretically be easy as in XML the document could be
seen simply as the outermost element, yet the API is counter-intuitive.
In other words how would you write the above function to take an Element
or a Node as an argument?
No comments:
Post a Comment