Here you can find the source of format(Node node, String indent)
Parameter | Description |
---|---|
node | For java, rather than GWT |
indent | a parameter |
public static String format(Node node, String indent)
//package com.java2s; /**//w ww.j av a2 s .co m * Copyright 2017 Institute of Computing Technology, Chinese Academy of Sciences. * Licensed under the terms of the Apache 2.0 license. * Please see LICENSE file in the project root for terms */ import org.w3c.dom.Document; import org.w3c.dom.Node; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; public class Main { /** * Format generated xml doc by indentation * * @param node For java, rather than GWT * @param indent * @return */ public static String format(Node node, String indent) { StringBuilder formatted = new StringBuilder(); if (node.getNodeType() == Node.ELEMENT_NODE) { StringBuilder attributes = new StringBuilder(); for (int k = 0; k < node.getAttributes().getLength(); k++) { attributes.append(" "); attributes.append(node.getAttributes().item(k).getNodeName()); attributes.append("=\""); attributes.append(node.getAttributes().item(k).getNodeValue()); attributes.append("\""); } formatted.append(indent); formatted.append("<"); formatted.append(node.getNodeName()); formatted.append(attributes.toString()); if (!node.hasChildNodes()) { formatted.append("/>\n"); return formatted.toString(); } if ((node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE)) { formatted.append(">"); } else { formatted.append(">\n"); } for (int i = 0; i < node.getChildNodes().getLength(); i++) { formatted.append(format(node.getChildNodes().item(i), indent + " ")); } if (node.hasChildNodes() && node.getFirstChild().getNodeType() != Node.TEXT_NODE) { formatted.append(indent); } formatted.append("</"); formatted.append(node.getNodeName()); formatted.append(">\n"); } else { String value = node.getTextContent().trim(); if (value.length() > 0) { formatted.append(value); } } return formatted.toString(); } /** Transform a XML Document to String */ public static String toString(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } } }