KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > io > xml > DomWriter


1 package com.thoughtworks.xstream.io.xml;
2
3 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
4 import org.w3c.dom.Document JavaDoc;
5 import org.w3c.dom.Element JavaDoc;
6 import org.w3c.dom.Node JavaDoc;
7
8 /**
9  * @author Michael Kopp
10  */

11 public class DomWriter implements HierarchicalStreamWriter {
12     private final Document JavaDoc document;
13     private Element JavaDoc current;
14
15     public DomWriter(Document JavaDoc document) {
16         this.document = document;
17         this.current = document.getDocumentElement();
18     }
19
20     public DomWriter(Element JavaDoc rootElement) {
21         document = rootElement.getOwnerDocument();
22         current = rootElement;
23     }
24
25     public void startNode(String JavaDoc name) {
26         final Element JavaDoc child = document.createElement(name);
27         if (current == null) {
28             document.appendChild(child);
29         } else {
30             current.appendChild(child);
31         }
32         current = child;
33     }
34
35     public void addAttribute(String JavaDoc name, String JavaDoc value) {
36         current.setAttribute(name, value);
37     }
38
39     public void setValue(String JavaDoc text) {
40         current.appendChild(document.createTextNode(text));
41     }
42
43     public void endNode() {
44         Node JavaDoc parent = current.getParentNode();
45         current = parent instanceof Element JavaDoc ? (Element JavaDoc)parent : null;
46     }
47
48     public void flush() {
49         // don't need to do anything
50
}
51
52     public void close() {
53         // don't need to do anything
54
}
55
56     public HierarchicalStreamWriter underlyingWriter() {
57         return this;
58     }
59 }
Popular Tags