Java XML Node to String toXml(Node node, boolean keepHeader)

Here you can find the source of toXml(Node node, boolean keepHeader)

Description

to Xml

License

Apache License

Declaration

public static String toXml(Node node, boolean keepHeader) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Node;

public class Main {

    public static String toXml(Node node, boolean keepHeader) throws Exception {
        Transformer transformer;/*from   ww w . j a  va 2  s . c  o  m*/
        DOMSource xmlSource = new DOMSource(node);
        transformer = TransformerFactory.newInstance().newTransformer();
        StringWriter writer = new StringWriter();
        StreamResult outputTarget = new StreamResult(writer);
        transformer.transform(xmlSource, outputTarget);
        String str = writer.getBuffer().toString();

        if (!keepHeader)
            return str.substring(str.indexOf("?>") + 2);
        else
            return str;
    }

    public static String toString(Object obj) {
        if (null == obj)
            return null;

        return String.valueOf(obj);
    }

    /**
     * Code copied from HtmlUnit
     * (src/main/java/com/gargoylesoftware/htmlunit/StringUtils.java)
     * (https://htmlunit.svn.sourceforge.net/svnroot/htmlunit/trunk/htmlunit -
     * commit 5556)
     */
    public static int indexOf(final String s, final char searchChar, final int beginIndex, final int endIndex) {
        for (int i = beginIndex; i < endIndex; i++) {
            if (s.charAt(i) == searchChar) {
                return i;
            }
        }
        return -1;
    }
}

Related

  1. toWriter(Node node, Writer writer, Map outputProperties)
  2. toXML(Node node)
  3. toXml(Node node)
  4. toXml(Node node)
  5. toXML(Node node)
  6. toXMLString(final Node value)
  7. toXMLString(Node node)
  8. toXMLString(Node node)
  9. toXMLString(Node node)