Debian Codegraph @

net/sf/saxon/dom/DOMWriter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.dom;
9
10 import net.sf.saxon.event.Builder;
11 import net.sf.saxon.event.PipelineConfiguration;
12 import net.sf.saxon.event.ReceiverOptions;
13 import net.sf.saxon.expr.parser.Location;
14 import net.sf.saxon.lib.NamespaceConstant;
15 import net.sf.saxon.om.*;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.type.SchemaType;
18 import net.sf.saxon.type.SimpleType;
19 import net.sf.saxon.value.Whitespace;
20 import org.w3c.dom.*;
21
22 import javax.xml.parsers.DocumentBuilderFactory;
23 import javax.xml.parsers.ParserConfigurationException;
24
25
26 /**
27 * DOMWriter is a Receiver that attaches the result tree to a specified Node in the DOM Document
28 */
29
30 public class DOMWriter extends Builder {
31
32 private PipelineConfiguration pipe;
33 private Node currentNode;
34 /*@Nullable*/ private Document document;
35 private Node nextSibling;
36 private int level = 0;
37 private boolean canNormalize = true;
38 private String systemId;
39
40 /**
41 * Set the pipelineConfiguration
42 */
43
44 public void setPipelineConfiguration(/*@NotNull*/ PipelineConfiguration pipe) {
45 this.pipe = pipe;
46 config = pipe.getConfiguration();
47 }
48
49 /**
50 * Get the pipeline configuration used for this document
51 */
52
53 /*@NotNull*/
54 public PipelineConfiguration getPipelineConfiguration() {
55 return pipe;
56 }
57
58 /**
59 * Set the System ID of the destination tree
60 */
61
62 public void setSystemId(String systemId) {
63 this.systemId = systemId;
64 }
65
66 /**
67 * Notify an unparsed entity URI.
68 *
69 * @param name The name of the unparsed entity
70 * @param systemID The system identifier of the unparsed entity
71 * @param publicID The public identifier of the unparsed entity
72 */
73
74 public void setUnparsedEntity(String name, String systemID, String publicID) throws XPathException {
75 // no-op
76 }
77
78 /**
79 * Get the system identifier that was set with setSystemId.
80 *
81 * @return The system identifier that was set with setSystemId,
82 * or null if setSystemId was not called.
83 */
84 public String getSystemId() {
85 return systemId;
86 }
87
88 /**
89 * Start of the document.
90 */
91
92 public void open() {
93 }
94
95 /**
96 * End of the document.
97 */
98
99 public void close() {
100 }
101
102 /**
103 * Start of a document node.
104 */
105
106 public void startDocument(int properties) throws XPathException {
107 if (document == null) {
108 try {
109 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
110 factory.setNamespaceAware(true);
111 document = factory.newDocumentBuilder().newDocument();
112 currentNode = document;
113 } catch (ParserConfigurationException err) {
114 throw new XPathException(err);
115 }
116 }
117 }
118
119 /**
120 * Notify the end of a document node
121 */
122
123 public void endDocument() throws XPathException {
124 }
125
126 /**
127 * Start of an element.
128 */
129
130 public void startElement(NodeName nameCode, SchemaType typeCode, Location location, int properties) throws XPathException {
131 String qname = nameCode.getDisplayName();
132 String uri = nameCode.getURI();
133 try {
134 Element element = document.createElementNS("".equals(uri) ? null : uri, qname);
135 if (nextSibling != null && level == 0) {
136 currentNode.insertBefore(element, nextSibling);
137 } else {
138 currentNode.appendChild(element);
139 }
140 currentNode = element;
141 } catch (DOMException err) {
142 throw new XPathException(err);
143 }
144 level++;
145 }
146
147 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
148 try {
149 for (NamespaceBinding ns : namespaceBindings) {
150 String prefix = ns.getPrefix();
151 String uri = ns.getURI();
152 Element element = (Element) currentNode;
153 if (!uri.equals(NamespaceConstant.XML)) {
154 if (prefix.isEmpty()) {
155 element.setAttributeNS(NamespaceConstant.XMLNS, "xmlns", uri);
156 } else {
157 element.setAttributeNS(NamespaceConstant.XMLNS, "xmlns:" + prefix, uri);
158
159 }
160 }
161 }
162 } catch (DOMException err) {
163 throw new XPathException(err);
164 }
165 }
166
167 public void attribute(NodeName nameCode, SimpleType typeCode, CharSequence value, Location locationId, int properties)
168 throws XPathException {
169 String qname = nameCode.getDisplayName();
170 String uri = nameCode.getURI();
171 try {
172 Element element = (Element) currentNode;
173 element.setAttributeNS("".equals(uri) ? null : uri, qname, value.toString());
174 if (nameCode.equals(StandardNames.XML_ID_NAME) ||
175 (properties & ReceiverOptions.IS_ID) != 0 ||
176 nameCode.hasURI(NamespaceConstant.XML) && nameCode.getLocalPart().equals("id")) {
177 String localName = nameCode.getLocalPart();
178 element.setIdAttributeNS("".equals(uri) ? null : uri, localName, true);
179 }
180 } catch (DOMException err) {
181 throw new XPathException(err);
182 }
183 }
184
185 public void startContent() throws XPathException {
186 }
187
188 /**
189 * End of an element.
190 */
191
192 public void endElement() throws XPathException {
193 if (canNormalize) {
194 try {
195 currentNode.normalize();
196 } catch (Throwable err) {
197 canNormalize = false;
198 } // in case it's a Level 1 DOM
199 }
200
201 currentNode = currentNode.getParentNode();
202 level--;
203 }
204
205
206 /**
207 * Character data.
208 */
209
210 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
211 if (level == 0 && nextSibling == null && Whitespace.isWhite(chars)) {
212 return; // no action for top-level whitespace
213 }
214 try {
215 Text text = document.createTextNode(chars.toString());
216 if (nextSibling != null && level == 0) {
217 currentNode.insertBefore(text, nextSibling);
218 } else {
219 currentNode.appendChild(text);
220 }
221 } catch (DOMException err) {
222 throw new XPathException(err);
223 }
224 }
225
226
227 /**
228 * Handle a processing instruction.
229 */
230
231 public void processingInstruction(String target, CharSequence data, Location locationId, int properties)
232 throws XPathException {
233 try {
234 ProcessingInstruction pi =
235 document.createProcessingInstruction(target, data.toString());
236 if (nextSibling != null && level == 0) {
237 currentNode.insertBefore(pi, nextSibling);
238 } else {
239 currentNode.appendChild(pi);
240 }
241 } catch (DOMException err) {
242 throw new XPathException(err);
243 }
244 }
245
246 /**
247 * Handle a comment.
248 */
249
250 public void comment(CharSequence chars, Location locationId, int properties) throws XPathException {
251 try {
252 Comment comment = document.createComment(chars.toString());
253 if (nextSibling != null && level == 0) {
254 currentNode.insertBefore(comment, nextSibling);
255 } else {
256 currentNode.appendChild(comment);
257 }
258 } catch (DOMException err) {
259 throw new XPathException(err);
260 }
261 }
262
263 /**
264 * Ask whether this Receiver (or the downstream pipeline) makes any use of the type annotations
265 * supplied on element and attribute events
266 *
267 * @return true if the Receiver makes any use of this information. If false, the caller
268 * may supply untyped nodes instead of supplying the type annotation
269 */
270
271 public boolean usesTypeAnnotations() {
272 return false;
273 }
274
275 /**
276 * Set the attachment point for the new subtree
277 *
278 * @param node the node to which the new subtree will be attached
279 */
280
281 public void setNode(Node node) {
282 if (node == null) {
283 return;
284 }
285 currentNode = node;
286 if (node.getNodeType() == Node.DOCUMENT_NODE) {
287 document = (Document) node;
288 } else {
289 document = currentNode.getOwnerDocument();
290 if (document == null) {
291 // which might be because currentNode() is a parentless ElementOverNodeInfo.
292 // we create a DocumentOverNodeInfo, which is immutable, and will cause the DOMWriter to fail
293 document = new DocumentOverNodeInfo();
294 }
295 }
296 }
297
298 /**
299 * Set next sibling
300 *
301 * @param nextSibling the node, which must be a child of the attachment point, before which the new subtree
302 * will be created. If this is null the new subtree will be added after any existing children of the
303 * attachment point.
304 */
305
306 public void setNextSibling(Node nextSibling) {
307 this.nextSibling = nextSibling;
308 }
309
310 /**
311 * Get the current root node. This will normally be a document node, but if the root of the tree
312 * is an element node, it can be an element.
313 *
314 * @return the root of the tree that is currently being built, or that has been most recently built
315 * using this builder
316 */
317
318 @Override
319 public NodeInfo getCurrentRoot() {
320 return new DocumentWrapper(document, systemId, config).getRootNode();
321 }
322
323 /**
324 * Get the constructed DOM Document node
325 * @return the DOM Document node
326 */
327
328 protected Document getDOMDocumentNode() {
329 return document;
330 }
331 }
332