Java XML Document to String documentToString(Document doc)

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

Description

Helper method which converts XML Document into pretty formatted string

License

Open Source License

Parameter

Parameter Description
doc to convert

Return

converted XML as String

Declaration

public static String documentToString(Document doc) 

Method Source Code

//package com.java2s;
/**/*  ww  w . ja  v a2  s  .c o  m*/
 * Copyright (c) 2010-2015, openHAB.org and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.w3c.dom.Document;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class Main {
    /***
     * Helper method which converts XML Document into pretty formatted string
     * @param doc to convert
     * @return converted XML as String
     */
    public static String documentToString(Document doc) {
        String strMsg = "";
        OutputFormat format = new OutputFormat(doc);
        format.setIndenting(true);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        try {
            serializer.serialize(doc);
            strMsg = baos.toString("UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strMsg;
    }
}

Related

  1. documentToString(Document doc)
  2. documentToString(Document doc)
  3. documentToString(Document doc)
  4. documentToString(Document doc)
  5. documentToString(Document doc)
  6. documentToString(Document document)
  7. documentToString(Document document)
  8. documentToString(Document document)
  9. documentToString(Document document)