01: /*
02: * Copyright (C) 2004, 2005, 2006 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 02. September 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.io.xml;
13:
14: import org.w3c.dom.Document;
15: import org.w3c.dom.Element;
16:
17: /**
18: * @author Michael Kopp
19: */
20: public class DomWriter extends AbstractDocumentWriter {
21:
22: private final Document document;
23: private boolean hasRootElement;
24:
25: public DomWriter(final Document document) {
26: this (document, new XmlFriendlyReplacer());
27: }
28:
29: public DomWriter(final Element rootElement) {
30: this (rootElement, new XmlFriendlyReplacer());
31: }
32:
33: /**
34: * @since 1.2
35: */
36: public DomWriter(final Document document,
37: final XmlFriendlyReplacer replacer) {
38: this (document.getDocumentElement(), document, replacer);
39: }
40:
41: /**
42: * @since 1.2.1
43: */
44: public DomWriter(final Element element, final Document document,
45: final XmlFriendlyReplacer replacer) {
46: super (element, replacer);
47: this .document = document;
48: hasRootElement = document.getDocumentElement() != null;
49: }
50:
51: /**
52: * @since 1.2
53: */
54: public DomWriter(final Element rootElement,
55: final XmlFriendlyReplacer replacer) {
56: this (rootElement.getOwnerDocument(), replacer);
57: }
58:
59: protected Object createNode(final String name) {
60: final Element child = document
61: .createElement(escapeXmlName(name));
62: final Element top = top();
63: if (top != null) {
64: top().appendChild(child);
65: } else if (!hasRootElement) {
66: document.appendChild(child);
67: hasRootElement = true;
68: }
69: return child;
70: }
71:
72: public void addAttribute(final String name, final String value) {
73: top().setAttribute(escapeXmlName(name), value);
74: }
75:
76: public void setValue(final String text) {
77: top().appendChild(document.createTextNode(text));
78: }
79:
80: private Element top() {
81: return (Element) getCurrent();
82: }
83: }
|