From 2186bf987ce3223395b9a4f4888be3d09bb6f6e2 Mon Sep 17 00:00:00 2001 From: Georgy Litvinov Date: Thu, 26 Nov 2020 11:40:15 +0100 Subject: [PATCH] Added pretty print for XML Node --- src/main/java/pro/litvinovg/xml/Debug.java | 68 +++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/src/main/java/pro/litvinovg/xml/Debug.java b/src/main/java/pro/litvinovg/xml/Debug.java index 27026f5..09f0bf6 100644 --- a/src/main/java/pro/litvinovg/xml/Debug.java +++ b/src/main/java/pro/litvinovg/xml/Debug.java @@ -2,9 +2,30 @@ package pro.litvinovg.xml; import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; +import org.xml.sax.InputSource; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.File; +import java.io.FileInputStream; +import java.io.StringWriter; +import java.io.Writer; import com.sun.star.uno.XComponentContext; @@ -22,5 +43,50 @@ public class Debug { System.out.println(ste); } } - + public static void prettyPrintXml(Node node) { + printXMLNode(node, 0, true); + } + + public static void printXMLNode(Node node, int depth, boolean printText) { + if (node == null) { + return; + } + for (int i = 0; i < depth; i++) + System.out.print(" "); + if (node.getNodeType() == Node.TEXT_NODE) { + if (printText) { + System.out.println(node.getNodeValue()); + } else { + System.out.println("text"); + } + return; + } + System.out.print('<'); + System.out.print(node.getNodeName()); + NamedNodeMap attrs = node.getAttributes(); + if (attrs != null) { + for (int i = 0; i < attrs.getLength(); i++) { + Node attr = attrs.item(i); + System.out.print(' '); + System.out.print(attr.getNodeName()); + System.out.print("=\""); + System.out.print(attr.getNodeValue()); + System.out.print('"'); + } + } + NodeList children = node.getChildNodes(); + if (children == null || children.getLength() == 0) + System.out.println("/>"); + else { + System.out.println('>'); + int len = children.getLength(); + for (int i = 0; i < len; i++) { + printXMLNode(children.item(i), depth + 1, printText); + } + for (int i = 0; i < depth; i++) + System.out.print(" "); + System.out.println(""); + } + } + }