Java 怎么使用DOM生成XML报告摘要

2019年7月29日19:43:17Java 怎么使用DOM生成XML报告摘要已关闭评论 571 2024字阅读6分44秒

1.简介

Java 怎么使用DOM生成XML报告摘要?——请看下文。

2.示例代码

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

 
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main{
    public static void main(String[] argv) throws Exception{
        boolean timeout = true;
        boolean xmlreport = true;
        double elapsed = 2.45678;
        generateXMLReportSummary(timeout,xmlreport,elapsed);
    }
    static Document doc;
    static void generateXMLReportSummary(boolean timeout,
            boolean xmlreport, double elapsed)
            throws TransformerFactoryConfigurationError {
        try {
            
            LeeRouter.obtainStats(null, elapsed, xmlreport);

            
            LeeRouter.xmlReport(doc);

            Element root = doc.getDocumentElement();
            Element element = doc.createElement("ElapsedTime");
            element.setTextContent(Double.toString(elapsed));
            root.appendChild(element);

            element = doc.createElement("Timeout");
            element.setTextContent(Boolean.toString(timeout));
            root.appendChild(element);

            
            DOMSource domSource = new DOMSource(doc);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();

            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer
                    .setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
            transformer.setOutputProperty(
                    "{http:
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            StreamResult sr = new StreamResult(sw);
            transformer.transform(domSource, sr);
            System.out.println(sw.toString());
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

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