create Default Message as XML DOM Document - Java XML

Java examples for XML:DOM

Description

create Default Message as XML DOM Document

Demo Code


//package com.java2s;
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 = "java2s.com";
        System.out.println(createDefaultMessage(messagetype));
    }/* w w  w  . ja va  2 s  .c  o  m*/

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

Related Tutorials