import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOMPrettyPrinter {
public static void prettyPrint(Document doc, int indentLevel) {
try {
prettyPrintHelper(doc, indentLevel);
} catch (Exception e) {
System.err.println("Error during pretty printing: " + e.getMessage());
e.printStackTrace(); // Log the stack trace for debugging
}
}
private static void prettyPrintHelper(Document doc, int indentLevel) throws Exception {
for (int i = 0; i < indentLevel; i++) {
System.out.print(" "); // Indentation
}
if (doc.getDocumentElement() == null) {
System.out.println("(Document with no root element)");
return;
}
Node root = doc.getDocumentElement();
System.out.println(root.getNodeName());
if (root.hasChildNodes()) {
NodeList children = root.childNodes;
for (int i = 0; i < children.length; i++) {
Node child = children.item(i);
prettyPrintHelper(child.asDocument(), indentLevel + 1);
}
}
}
public static void main(String[] args) {
// Example usage (replace with your DOM)
try {
Document doc = createSampleDOM();
prettyPrint(doc, 0);
} catch (Exception e) {
System.err.println("Error creating sample DOM: " + e.getMessage());
e.printStackTrace();
}
}
private static Document createSampleDOM() {
Document doc = Document.createDocument(null, "root", null);
Node node1 = doc.createElement("div");
doc.appendChild(node1);
Node node2 = doc.createElement("p");
node1.appendChild(node2);
node2.appendChild(doc.createTextNode("This is a paragraph."));
Node node3 = doc.createElement("ul");
node1.appendChild(node3);
NodeList listItems = doc.createDocumentFragment().getChildren(node3);
for (int i = 0; i < 3; i++) {
Node listItem = doc.createElement("li");
node3.appendChild(listItem);
listItem.appendChild(doc.createTextNode("Item " + (i + 1)));
}
return doc;
}
}
Add your comment