Java 怎么返回XML元素的字符串表示形式

2019年8月11日20:49:40Java 怎么返回XML元素的字符串表示形式已关闭评论 375 1094字阅读3分38秒

1.简介

Java 怎么返回XML元素的字符串表示形式?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 

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();
            }
        }
    }
}

 
继续阅读
编程十万个怎么办