Java XML Element to String elementToString(Element element)

Here you can find the source of elementToString(Element element)

Description

Converts an Element object into String representation

License

Open Source License

Parameter

Parameter Description
element a parameter

Exception

Parameter Description
TransformerException an exception

Declaration

public static String elementToString(Element element) throws TransformerException 

Method Source Code

//package com.java2s;
/**/*from  w w w .  ja v a2  s . c  om*/
 * (C) Copyright 2015 Zaizi Limited (http://www.zaizi.com).
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 3.0 which accompanies this distribution, and is available at 
 * http://www.gnu.org/licenses/lgpl-3.0.en.html
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 **/

import org.w3c.dom.Element;

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 java.io.StringWriter;

public class Main {
    /**
     * <p>Converts an {@code Element} object into {@code String} representation</p>
     * @param element
     * @return
     * @throws TransformerException
     */
    public static String elementToString(Element element) throws TransformerException {
        DOMSource domSource = new DOMSource(element);
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(domSource, streamResult);

        return stringWriter.toString();
    }
}

Related

  1. elementToStream(Element element, OutputStream out)
  2. elementToStream(Element element, OutputStream out)
  3. elementToString(Element e)
  4. elementToString(Element el)
  5. elementToString(Element element)
  6. elementToString(Element element)
  7. elementToString(Element elt, String prefix)
  8. elementToString(final Element element)