Java Reference
In-Depth Information
Creating XML for the Document Body
The recursive getDocumentNode() method to assemble the XML for the document body is a little
more work than the others but it will work much like the method we wrote earlier to list nodes in a
document. The method will find out the specific type of the current node then append the appropriate
XML string to a StringBuffer object. If the current node has child nodes, the method will call itself
to deal with each of these nodes. We can implement the writeDocumentNode() method like this:
private String getDocumentNode(Node node, String indent) {
StringBuffer nodeStr = new StringBuffer().append(NEWLINE).append(indent);
String nodeName = node.getNodeName(); // Get name of this node
switch(node.getNodeType()) {
case Node.ELEMENT _ NODE:
nodeStr.append(TAG _ START);
nodeStr.append(nodeName);
if(node.hasAttributes()) { // If the element has attributes...
org.w3c.dom.NamedNodeMap attrs = node.getAttributes(); // ...get them
for(int i = 0 ; i<attrs.getLength() ; i++) {
org.w3c.dom.Attr attribute = (org.w3c.dom.Attr)attrs.item(i);
// Append " name="value" to the element string
nodeStr.append(' ').append(attribute.getName()).append('=')
.append(QUOTE).append(attribute.getValue()).append(QUOTE);
}
}
if(!node.hasChildNodes()) { // Check for no children for this element
nodeStr.append(EMPTY _ TAG _ END); // There are none-close as empty element
return nodeStr.toString(); // and return the completed element
} else { // It has children
nodeStr.append(TAG _ END); // so close start-tag
NodeList list = node.getChildNodes(); // Get the list of child nodes
assert list.getLength()>0; // There must be at least one
// Append child nodes and their children...
for(int i = 0 ; i<list.getLength() ; i++)
nodeStr.append(getDocumentNode(list.item(i), indent+" "));
}
nodeStr.append(NEWLINE).append(indent).append(END _ TAG _ START)
.append(nodeName).append(TAG _ END);
break;
case Node.TEXT _ NODE:
nodeStr.append(replaceQuotes(((org.w3c.dom.Text)node).getData()));
break;
default:
assert false;
}
return nodeStr.toString();
}
Search WWH ::




Custom Search