Java tutorial
//package com.java2s; /* * * $Date$ * $Author$ * $Revision$ * * Copyright 2010 the University of New Mexico. * * This work was supported by National Science Foundation Cooperative * Agreements #DEB-0832652 and #DEB-0936498. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * */ import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; 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 org.w3c.dom.Node; public class Main { /** * Returns an XML representation of the provided node. * * @param node the node to be represented in XML. * * @return a string containing an XML representation of the * provided DOM node. */ public static String nodeToXmlString(Node node) { try { Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(node); StreamResult result = new StreamResult(new StringWriter()); t.transform(source, result); return result.getWriter().toString(); } catch (TransformerException e) { throw new IllegalStateException(e); } catch (TransformerFactoryConfigurationError e) { throw new IllegalStateException(e); } } }