KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.thoughtworks.xstream.io.xml;
2
3 import java.util.List JavaDoc;
4 import java.util.LinkedList JavaDoc;
5
6 import org.jdom.Element;
7 import org.jdom.JDOMFactory;
8 import org.jdom.DefaultJDOMFactory;
9
10 import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
11
12 /**
13  * @author Laurent Bihanic
14  */

15 public class JDomWriter implements HierarchicalStreamWriter {
16
17     private List JavaDoc result = new LinkedList JavaDoc();
18     private List JavaDoc elementStack = new LinkedList JavaDoc();
19     private final JDOMFactory documentFactory;
20
21     public JDomWriter(Element container, JDOMFactory factory) {
22         elementStack.add(0, container);
23         this.result.add(container);
24         this.documentFactory = factory;
25     }
26
27     public JDomWriter(JDOMFactory documentFactory) {
28         this.documentFactory = documentFactory;
29     }
30
31     public JDomWriter(Element container) {
32         this(container, new DefaultJDOMFactory());
33     }
34
35     public JDomWriter() {
36         this(new DefaultJDOMFactory());
37     }
38
39     public void startNode(String JavaDoc name) {
40         Element element = this.documentFactory.element(name);
41
42         Element parent = this.top();
43         if (parent != null) {
44             parent.addContent(element);
45         }
46         else {
47             this.result.add(element);
48         }
49         elementStack.add(0, element);
50     }
51
52     public void setValue(String JavaDoc text) {
53         this.top().addContent(this.documentFactory.text(text));
54     }
55
56     public void addAttribute(String JavaDoc key, String JavaDoc value) {
57         ((Element) this.top()).setAttribute(
58                         this.documentFactory.attribute(key, value));
59     }
60
61     public void endNode() {
62         this.elementStack.remove(0);
63     }
64
65     private Element top() {
66         Element top = null;
67
68         if (this.elementStack.isEmpty() == false) {
69             top = (Element) this.elementStack.get(0);
70         }
71         return top;
72     }
73
74     public List JavaDoc getResult() {
75         return this.result;
76     }
77
78     public void flush() {
79         // don't need to do anything
80
}
81
82     public void close() {
83         // don't need to do anything
84
}
85
86     public HierarchicalStreamWriter underlyingWriter() {
87         return this;
88     }
89 }
90
Popular Tags