Returns the String representation of XML Element. - Java XML

Java examples for XML:XML Element Value

Description

Returns the String representation of XML Element.

Demo Code

/**/* w  w w . j av  a  2s .  c  o  m*/
 * Copyright 2012 Jos? Mart?nez
 * 
 * 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.
 */
//package com.java2s;
import java.io.IOException;

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 {
    private final static TransformerFactory transformFactory = TransformerFactory
            .newInstance();

    public static final String toString(final Element element) {

        final StringWriter buffer = new StringWriter();
        try {
            Transformer transform = transformFactory.newTransformer();

            transform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");

            transform.setOutputProperty(OutputKeys.INDENT, "no");

            transform.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

            transform.transform(new DOMSource(element), new StreamResult(
                    buffer));

            return buffer.toString();
        } catch (final TransformerException e) {
            throw new InternalError("Transformer error");
        } finally {
            buffer.flush();
            try {
                buffer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related Tutorials