Java Reference
In-Depth Information
Example 19−4: XMLDocumentWriter.java (continued)
case Node.DOCUMENT_TYPE_NODE: { // It is a <!DOCTYPE> tag
DocumentType doctype = (DocumentType) node;
// Note that the DOM Level 1 does not give us information about
// the the public or system ids of the doctype, so we can't output
// a complete <!DOCTYPE> tag here. We can do better with Level 2.
out.println("<!DOCTYPE " + doctype.getName() + ">");
break;
}
case Node.ELEMENT_NODE: {
// Most nodes are Elements
Element elt = (Element) node;
out.print(indent + "<" + elt.getTagName()); // Begin start tag
NamedNodeMap attrs = elt.getAttributes(); // Get attributes
for(int i = 0; i < attrs.getLength(); i++) { // Loop through them
Node a = attrs.item(i);
out.print(" " + a.getNodeName() + "='" + // Print attr. name
fixup(a.getNodeValue()) + "'"); // Print attr. value
}
out.println(">");
// Finish start tag
String newindent = indent + "
";
// Increase indent
Node child = elt.getFirstChild();
// Get child
while(child != null) {
// Loop
write(child, newindent);
// Output child
child = child.getNextSibling();
// Get next child
}
out.println(indent + "</" +
// Output end tag
elt.getTagName() + ">");
break;
}
case Node.TEXT_NODE: {
// Plain text node
Text textNode = (Text)node;
String text = textNode.getData().trim();
// Strip off space
if ((text != null) && text.length() > 0)
// If non-empty
out.println(indent + fixup(text));
// print text
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: { // Handle PI nodes
ProcessingInstruction pi = (ProcessingInstruction)node;
out.println(indent + "<?" + pi.getTarget() +
" " + pi.getData() + "?>");
break;
}
case Node.ENTITY_REFERENCE_NODE: { // Handle entities
out.println(indent + "&" + node.getNodeName() + ";");
break;
}
case Node.CDATA_SECTION_NODE: { // Output CDATA sections
CDATASection cdata = (CDATASection)node;
// Careful! Don't put a CDATA section in the program itself!
out.println(indent + "<" + "![CDATA[" + cdata.getData() +
"]]" + ">");
break;
}
case Node.COMMENT_NODE: {
// Comments
Comment c = (Comment)node;
out.println(indent + "<!--" + c.getData() + "-->");
break;
Search WWH ::




Custom Search