Java XML Element to String getXmlString(Element node)

Here you can find the source of getXmlString(Element node)

Description

get Xml String

License

Apache License

Declaration

public static String getXmlString(Element node) 

Method Source Code

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

import java.io.StringWriter;

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.DOMImplementation;

import org.w3c.dom.Element;

import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;

public class Main {
    public static String getXmlString(Element node) {
        return toString(node);
    }//  www  .j ava  2 s  .c o m

    public static String toString(Element element) {
        DOMImplementation impl = element.getOwnerDocument().getImplementation();
        if (impl.hasFeature("LS", "3.0")) {
            DOMImplementationLS lsImpl = (DOMImplementationLS) impl.getFeature("LS", "3.0");
            LSSerializer serializer = lsImpl.createLSSerializer();
            serializer.getDomConfig().setParameter("xml-declaration", false); //by default its true, so set it to false to get String without xml-declaration
            return serializer.writeToString(element);
        } else {
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                StringWriter stringWriter = new StringWriter();
                transformer.transform(new DOMSource(element), new StreamResult(stringWriter));
                return stringWriter.toString();
            } catch (TransformerException e) {
                e.printStackTrace();
                return "<unableToSerialize/>";
            }
        }
    }
}

Related

  1. getStringValue(Element from)
  2. getStringValue(final Element element)
  3. getStringValueByTagName(Element element, String tagName)
  4. getStringValueOfElement(Element elem)
  5. getStringValues(Element from, String elementName)
  6. getXMLStringFromNode(Element node)
  7. toString(Element e)
  8. toString(Element element)
  9. toString(Element node)