Java XML Node to String asString(Element elt)

Here you can find the source of asString(Element elt)

Description

as String

License

Open Source License

Declaration

private static String asString(Element elt) 

Method Source Code

//package com.java2s;
/**//from  www. j a v  a2s .co  m
 * Copyright (c) 2011-2014 INRIA.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>
 **/

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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.Element;

public class Main {
    private static String asString(Element elt) {
        TransformerFactory transfac = TransformerFactory.newInstance();

        try {
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.setOutputProperty(
                    "{http://xml.apache.org/xslt}indent-amount", "4");

            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(elt);

            try {
                trans.transform(source, result);
                return sw.toString();
            } catch (TransformerException e) {
                throw new IllegalStateException(e);
            }

        } catch (TransformerConfigurationException e) {
            throw new IllegalStateException(e);
        }
    }
}

Related

  1. asString(Node node)
  2. asString(Node node)
  3. asString(Node node)
  4. asString(XMLStreamReader xmlr)