Java 怎么将默认消息创建为XML DOM文档(Document)

2019年7月29日19:36:56Java 怎么将默认消息创建为XML DOM文档(Document)已关闭评论 303 962字阅读3分12秒

1.简介

Java 怎么将默认消息创建为XML DOM文档(Document)?——请看下文。

2.示例代码

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


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    public static void main(String[] argv) throws Exception {
        String messagetype = "tah1986.com";
        System.out.println(createDefaultMessage(messagetype));
    }

    static public Document createDefaultMessage(String messagetype) {
        DocumentBuilderFactory factory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder documentbuilder = null;
        try {
            documentbuilder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }

        Document doc = documentbuilder.newDocument();
        Element root = doc.createElement("message");
        doc.appendChild(root);
        long timestamp = System.currentTimeMillis();
        root.setAttribute("timestamp", Long.toString(timestamp));
        root.setAttribute("type", messagetype);
        return doc;
    }
}

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