1. import org.w3c.dom.Document;
  2. import org.w3c.dom.Node;
  3. import org.w3c.dom.NodeList;
  4. public class DOMPrettyPrinter {
  5. public static void prettyPrint(Document doc, int indentLevel) {
  6. try {
  7. prettyPrintHelper(doc, indentLevel);
  8. } catch (Exception e) {
  9. System.err.println("Error during pretty printing: " + e.getMessage());
  10. e.printStackTrace(); // Log the stack trace for debugging
  11. }
  12. }
  13. private static void prettyPrintHelper(Document doc, int indentLevel) throws Exception {
  14. for (int i = 0; i < indentLevel; i++) {
  15. System.out.print(" "); // Indentation
  16. }
  17. if (doc.getDocumentElement() == null) {
  18. System.out.println("(Document with no root element)");
  19. return;
  20. }
  21. Node root = doc.getDocumentElement();
  22. System.out.println(root.getNodeName());
  23. if (root.hasChildNodes()) {
  24. NodeList children = root.childNodes;
  25. for (int i = 0; i < children.length; i++) {
  26. Node child = children.item(i);
  27. prettyPrintHelper(child.asDocument(), indentLevel + 1);
  28. }
  29. }
  30. }
  31. public static void main(String[] args) {
  32. // Example usage (replace with your DOM)
  33. try {
  34. Document doc = createSampleDOM();
  35. prettyPrint(doc, 0);
  36. } catch (Exception e) {
  37. System.err.println("Error creating sample DOM: " + e.getMessage());
  38. e.printStackTrace();
  39. }
  40. }
  41. private static Document createSampleDOM() {
  42. Document doc = Document.createDocument(null, "root", null);
  43. Node node1 = doc.createElement("div");
  44. doc.appendChild(node1);
  45. Node node2 = doc.createElement("p");
  46. node1.appendChild(node2);
  47. node2.appendChild(doc.createTextNode("This is a paragraph."));
  48. Node node3 = doc.createElement("ul");
  49. node1.appendChild(node3);
  50. NodeList listItems = doc.createDocumentFragment().getChildren(node3);
  51. for (int i = 0; i < 3; i++) {
  52. Node listItem = doc.createElement("li");
  53. node3.appendChild(listItem);
  54. listItem.appendChild(doc.createTextNode("Item " + (i + 1)));
  55. }
  56. return doc;
  57. }
  58. }

Add your comment