Java 怎么返回与给定XML文档对应的字符串表示形式

2019年7月29日19:31:44Java 怎么返回与给定XML文档对应的字符串表示形式已关闭评论 477 1032字阅读3分26秒

1.简介

Java 怎么返回与给定XML文档对应的字符串表示形式?——请看下文。

2.示例代码

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



import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
    
    public static String stringify(Document doc, boolean prettyprint) {
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            if (prettyprint)
                factory.setAttribute("indent-number", 2);

            Transformer transformer = factory.newTransformer();
            if (prettyprint)
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter writer = new StringWriter();
            Result result = new StreamResult(writer);
            Source source = new DOMSource(doc);
            transformer.transform(source, result);
            writer.flush();
            writer.close();
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    
    public static String stringify(Document doc) {
        return stringify(doc, false);
    }
}

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