Added pretty print for XML Node
This commit is contained in:
parent
0d0432d8d8
commit
2186bf987c
1 changed files with 67 additions and 1 deletions
|
@ -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("</" + node.getNodeName() + ">");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue