Java XML Document to String getXml(Document doc)

Here you can find the source of getXml(Document doc)

Description

get Xml

License

Apache License

Declaration

public static String getXml(Document doc) 

Method Source Code

//package com.java2s;
/* //w  w w .  j av a2 s . com
 * Licensed to the soi-toolkit project under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The soi-toolkit project licenses this file to You 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.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
    public static String getXml(Document doc) {
        try {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            //initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);

            String xmlString = result.getWriter().toString();
            return xmlString;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. getStringFromXMLDocument(Document doc)
  2. getStringFromXPath(Document doc, XPath xpath, String expression)
  3. getStringListFromXPath(Document doc, XPath xpath, String rootNodeExpression, String listExpression)
  4. getStringRepresentation(DocumentFragment df)
  5. getXML(Document doc)
  6. getXML(Document pDocument)
  7. toByteArray(final Document document)
  8. toByteArray(final Document document)
  9. toStream(Document document, OutputStream stream)