Here you can find the source of getXmlAsString(Node node)
Parameter | Description |
---|---|
node | a parameter |
Parameter | Description |
---|---|
TransformerException | an exception |
public static String getXmlAsString(Node node) throws TransformerException
//package com.java2s; //License from project: Open Source License import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { /**/* w w w . j av a 2s.c om*/ * @param node * @return output of the node's xml string. * @throws TransformerException */ public static String getXmlAsString(Node node) throws TransformerException { Transformer transformer = getTransformer(); DOMSource source = new DOMSource(node); StringWriter xmlString = new StringWriter(); StreamResult streamResult = new StreamResult(xmlString); transformer.transform(source, streamResult); return xmlString.toString(); } private static Transformer getTransformer() throws TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); return transformer; } /** * * @param node * @return * @deprecated Use {@link #getXmlAsString(Node)} instead. */ public static String toString(Node node) { StringBuffer sb = new StringBuffer(); if (node instanceof Text) { if (node.getNodeValue() != null) { byte[] bytes = node.getNodeValue().getBytes(); List<Byte> newBytes = new ArrayList<Byte>(); for (int i = 0; i < bytes.length; i++) { if (bytes[i] == 63) { byte[] bs = " ".getBytes(); for (byte b : bs) { newBytes.add(b); } } else { newBytes.add(bytes[i]); } } byte[] valueBytes = new byte[newBytes.size()]; for (int i = 0; i < newBytes.size(); i++) { valueBytes[i] = newBytes.get(i).byteValue(); } sb.append(new String(valueBytes)); } } else { sb.append("<").append(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); for (int j = 0; j < attrs.getLength(); j++) { sb.append(" ").append(attrs.item(j).getNodeName()).append("=\"") .append(attrs.item(j).getNodeValue()).append("\""); } sb.append(">"); if (node.hasChildNodes()) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { String str = toString(children.item(i)); if (str != null) sb.append(str); } } else { sb.append(node.getNodeValue()); } sb.append("</").append(node.getNodeName()).append(">"); } return sb.toString(); } }