// Simple Java DOM XML Processing Example
// Source: http://www.genedavis.com/library/xml/java_dom_xml_creation.php
1
2
3 import java.io.*;
4
5 import org.w3c.dom.*;
6
7 import javax.xml.parsers.*;
8
9 import javax.xml.transform.*;
10 import javax.xml.transform.dom.*;
11 import javax.xml.transform.stream.*;
12
13 public class DomXmlExample {
14
15 /**
16 * Our goal is to create a DOM XML tree and then print the XML.
17 */
18 public static void main (String args[]) {
19 new DomXmlExample();
20 }
21
22 public DomXmlExample() {
23 try {
24 /////////////////////////////
25 // Creating an empty XML Document
26
27 // We need a Document
28 DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
29 DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
30 Document doc = docBuilder.newDocument();
31
32 ////////////////////////
33 // Creating the XML tree
34
35 // create the root element and add it to the document
36 Element root = doc.createElement("root");
37 doc.appendChild(root);
38
39 // create a comment and put it in the root element
40 Comment comment = doc.createComment("Just a thought");
41 root.appendChild(comment);
42
43 // create child element, add an attribute, and add to root
44 Element child = doc.createElement("child");
45 child.setAttribute("name", "value");
46 root.appendChild(child);
47
48 // add a text element to the child
49 Text text = doc.createTextNode("Filler, ... I could have had a foo!");
50 child.appendChild(text);
51
52 /////////////////
53 // Output the XML
54
55 // set up a transformer
56 TransformerFactory transfac = TransformerFactory.newInstance();
57 Transformer trans = transfac.newTransformer();
58 trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
59 trans.setOutputProperty(OutputKeys.INDENT, "yes");
60
61 // create string from xml tree
62 StringWriter sw = new StringWriter();
63 StreamResult result = new StreamResult(sw);
64 DOMSource source = new DOMSource(doc);
65 trans.transform(source, result);
66 String xmlString = sw.toString();
67
68 // print xml
69 System.out.println("Here's the xml:\n\n" + xmlString);
70
71 } catch (Exception e) {
72 System.out.println(e);
73 }
74 }
75 }