1 package com.thoughtworks.xstream.io.xml; 2 3 import java.util.List ; 4 import java.util.LinkedList ; 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 15 public class JDomWriter implements HierarchicalStreamWriter { 16 17 private List result = new LinkedList (); 18 private List elementStack = new LinkedList (); 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 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 text) { 53 this.top().addContent(this.documentFactory.text(text)); 54 } 55 56 public void addAttribute(String key, String 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 getResult() { 75 return this.result; 76 } 77 78 public void flush() { 79 } 81 82 public void close() { 83 } 85 86 public HierarchicalStreamWriter underlyingWriter() { 87 return this; 88 } 89 } 90 | Popular Tags |