Java tutorial
//package com.java2s; /* * Copyright 2012 Johns Hopkins University * * 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.IOException; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Node; public class Main { private static SAXTransformerFactory transformerFactory; public static String extractText(Node n) { StringBuffer buf = new StringBuffer(); extractText(n, buf); return buf.toString().trim(); } private static void extractText(Node n, StringBuffer buf) { if (n.getNodeType() == Node.TEXT_NODE) { buf.append(n.getNodeValue()); } for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) { extractText(n, buf); } } public static String toString(Node n) throws IOException, TransformerException { StringWriter w = new StringWriter(); serialize(n, new StreamResult(w)); return w.toString(); } public static void serialize(Node n, StreamResult sr) throws IOException, TransformerException { TransformerHandler hd = newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(n); serializer.transform(source, sr); } public static TransformerHandler newTransformerHandler() throws TransformerConfigurationException { if (transformerFactory == null) { transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); } return transformerFactory.newTransformerHandler(); } }