Java 怎么序列化XML文档

2019年7月27日23:28:01Java 怎么序列化XML文档已关闭评论 522 690字阅读2分18秒

1.简介

Java 怎么序列化XML文档?——请看下文。

2.示例代码

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

 

import java.io.*;

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import org.w3c.dom.*;

public class Main {
    public static String serializeDocument(Document document)
            throws Exception {
        
        StringWriter writer = new StringWriter();
        StreamResult streamResult = new StreamResult(writer);

        DOMSource domSource = new DOMSource(document);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.transform(domSource, streamResult);

        return writer.toString();
    }
}

 
编程十万个怎么办