Java XML Document to String xmlToString(Document doc)

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

Description

xml To String

License

Apache License

Declaration

public static String xmlToString(Document doc) 

Method Source Code

//package com.java2s;
/*//from   w  ww.java2 s  .  c o m
 * Copyright 2015 Alexandre Terrasa <alexandre@moz-code.org>.
 *
 * 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.StringWriter;

import javax.xml.transform.OutputKeys;
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.Document;

public class Main {
    public static String xmlToString(Document doc) {
        try {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
            return result.getWriter().toString();
        } catch (TransformerException ex) {
            System.err.println("Error: Cannot load xml transformer");
            System.err.println("Cause: " + ex.toString());
            System.exit(1);
            return null;
        }
    }
}

Related

  1. xmlDocumentToString(final Document document)
  2. xmlDocumentToString(Node d)
  3. xmlDOMDocumentToString(Document doc)
  4. XMLDOMtoString(Document document)
  5. xmlToFile(Document doc, String fileNameToWrite)
  6. XMLtoString(Document doc)
  7. xmlToString(Document doc)
  8. xmlToString(Document document)
  9. xmlToString(Document xml)