1
2
3
4
5
6
7
8 package org.dom4j.io;
9
10 import org.dom4j.Document;
11 import org.dom4j.Element;
12 import org.dom4j.ElementHandler;
13 import org.dom4j.ElementPath;
14
15 /***
16 * This {@link org.dom4j.ElementHandler}is used to trigger {@link
17 * ElementModifier} objects in order to modify (parts of) the Document on the
18 * fly.
19 *
20 * <p>
21 * When an element is completely parsed, a copy is handed to the associated (if
22 * any) {@link ElementModifier}that on his turn returns the modified element
23 * that has to come in the tree.
24 * </p>
25 *
26 * @author Wonne Keysers (Realsoftware.be)
27 */
28 class SAXModifyElementHandler implements ElementHandler {
29 private ElementModifier elemModifier;
30
31 private Element modifiedElement;
32
33 public SAXModifyElementHandler(ElementModifier elemModifier) {
34 this.elemModifier = elemModifier;
35 }
36
37 public void onStart(ElementPath elementPath) {
38 this.modifiedElement = elementPath.getCurrent();
39 }
40
41 public void onEnd(ElementPath elementPath) {
42 try {
43 Element origElement = elementPath.getCurrent();
44 Element currentParent = origElement.getParent();
45
46 if (currentParent != null) {
47
48 Element clonedElem = (Element) origElement.clone();
49
50
51 modifiedElement = elemModifier.modifyElement(clonedElem);
52
53 if (modifiedElement != null) {
54
55 modifiedElement.setParent(origElement.getParent());
56 modifiedElement.setDocument(origElement.getDocument());
57
58
59 int contentIndex = currentParent.indexOf(origElement);
60 currentParent.content().set(contentIndex, modifiedElement);
61 }
62
63
64 origElement.detach();
65 } else {
66 if (origElement.isRootElement()) {
67
68 Element clonedElem = (Element) origElement.clone();
69
70
71 modifiedElement = elemModifier.modifyElement(clonedElem);
72
73 if (modifiedElement != null) {
74
75 modifiedElement.setDocument(origElement.getDocument());
76
77
78 Document doc = origElement.getDocument();
79 doc.setRootElement(modifiedElement);
80 }
81
82
83 origElement.detach();
84 }
85 }
86
87
88
89 if (elementPath instanceof ElementStack) {
90 ElementStack elementStack = ((ElementStack) elementPath);
91 elementStack.popElement();
92 elementStack.pushElement(modifiedElement);
93 }
94 } catch (Exception ex) {
95 throw new SAXModifyException(ex);
96 }
97 }
98
99 /***
100 * DOCUMENT ME!
101 *
102 * @return Returns the modified Element.
103 */
104 protected Element getModifiedElement() {
105 return modifiedElement;
106 }
107 }
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144