Java XML Element to String elementToString(final Element element)

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

Description

Converts an Element into its XML String representation.

License

Open Source License

Parameter

Parameter Description
element XML element

Return

String representation of XML element

Declaration

private static String elementToString(final Element element) 

Method Source Code

//package com.java2s;
/*//www.j  a  va2 s  .  co  m
 * Copyright ? 2009-2016 The Apromore Initiative.
 *
 * This file is part of "Apromore".
 *
 * "Apromore" is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * "Apromore" 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.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>.
 */

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.Element;

public class Main {
    /**
     * Converts an Element into its XML String representation.
     *
     * @param element
     *            XML element
     * @return String representation of XML element
     */
    private static String elementToString(final Element element) {
        try {
            final DOMSource domSource = new DOMSource(element);
            final StringWriter writer = new StringWriter();
            final StreamResult result = new StreamResult(writer);
            final TransformerFactory tf = TransformerFactory.newInstance();
            final Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.transform(domSource, result);
            return writer.toString();
        } catch (final TransformerException e) {
            throw new IllegalArgumentException("Invalid Element!", e);
        }
    }
}

Related

  1. elementToString(Element el)
  2. elementToString(Element element)
  3. elementToString(Element element)
  4. elementToString(Element element)
  5. elementToString(Element elt, String prefix)
  6. extractText(Element element)
  7. extractText(Element obj, String localName)
  8. extractTextElementValue(final Element textElement)
  9. getElementAsInputStream(Element xml)