Java XML String Transform extractText(Node n, StringBuffer buf)

Here you can find the source of extractText(Node n, StringBuffer buf)

Description

extract Text

License

Apache License

Declaration

private static void extractText(Node n, StringBuffer buf) 

Method Source Code

//package com.java2s;
//License from project: Apache 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);/*from  w  w  w  .j  av  a 2 s  .c  om*/

        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 {
        TransformerHandler hd = newTransformerHandler();
        Transformer serializer = hd.getTransformer();

        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(n);
        StringWriter w = new StringWriter();
        StreamResult result = new StreamResult(w);

        serializer.transform(source, result);

        return w.toString();
    }

    public static TransformerHandler newTransformerHandler() throws TransformerConfigurationException {
        if (transformerFactory == null) {
            transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        }

        return transformerFactory.newTransformerHandler();
    }
}

Related

  1. encode(final String value)
  2. encodeStringIntoMemento(String str)
  3. escapeBackslashes(String value)
  4. extractAndNormalizeEmbedPictures(String xmlFile, String odtFile, String parentDir, String imgBaseDir)
  5. extractElement(String xml, String tagName)
  6. fileToXMLString(String filename)
  7. getAsXMLString(final Node node)
  8. getBeanDefinition(String beanId, File file)
  9. getConfigurationAsXML(Map properties)