Debian Codegraph @

net/sf/saxon/s9api/XdmNode.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.s9api;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.om.AtomicSequence;
12 import net.sf.saxon.om.NodeInfo;
13 import net.sf.saxon.om.StructuredQName;
14 import net.sf.saxon.pattern.NameTest;
15 import net.sf.saxon.query.QueryResult;
16 import net.sf.saxon.s9api.streams.Steps;
17 import net.sf.saxon.s9api.streams.XdmStream;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.iter.AxisIterator;
20 import net.sf.saxon.tree.wrapper.VirtualNode;
21 import net.sf.saxon.type.Type;
22
23 import javax.xml.transform.Source;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.util.function.Predicate;
27 import java.util.stream.Stream;
28
29 /**
30 * This class represents a node in the XDM data model. A Node is an {@link XdmItem}, and is therefore an
31 * {@link XdmValue} in its own right, and may also participate as one item within a sequence value.
32 * <p>An XdmNode is implemented as a wrapper around an object of type {@link net.sf.saxon.om.NodeInfo}.
33 * Because this is a key interface within Saxon, it is exposed via this API.</p>
34 * <p>The XdmNode interface exposes basic properties of the node, such as its name, its string value, and
35 * its typed value. Navigation to other nodes is supported through a single method, {@link #axisIterator},
36 * which allows other nodes to be retrieved by following any of the XPath axes.</p>
37 * <p>Note that node identity cannot be inferred from object identity. The same node may be represented
38 * by different <code>XdmNode</code> instances at different times, or even at the same time. The equals()
39 * method on this class can be used to test for node identity.</p>
40 *
41 * @since 9.0
42 */
43 public class XdmNode extends XdmItem {
44
45 private XdmNode() {}
46
47 /**
48 * Construct an XdmNode as a wrapper around an existing NodeInfo object
49 *
50 * @param node the NodeInfo object to be wrapped. This can be retrieved using the
51 * {@link #getUnderlyingNode} method.
52 * @since 9.2 (previously a protected constructor)
53 */
54
55 public XdmNode(NodeInfo node) {
56 setValue(node);
57 }
58
59 /**
60 * Get the kind of node.
61 *
62 * @return the kind of node, for example {@link XdmNodeKind#ELEMENT} or {@link XdmNodeKind#ATTRIBUTE}
63 */
64
65 public XdmNodeKind getNodeKind() {
66 switch (getUnderlyingNode().getNodeKind()) {
67 case Type.DOCUMENT:
68 return XdmNodeKind.DOCUMENT;
69 case Type.ELEMENT:
70 return XdmNodeKind.ELEMENT;
71 case Type.ATTRIBUTE:
72 return XdmNodeKind.ATTRIBUTE;
73 case Type.TEXT:
74 return XdmNodeKind.TEXT;
75 case Type.COMMENT:
76 return XdmNodeKind.COMMENT;
77 case Type.PROCESSING_INSTRUCTION:
78 return XdmNodeKind.PROCESSING_INSTRUCTION;
79 case Type.NAMESPACE:
80 return XdmNodeKind.NAMESPACE;
81 default:
82 throw new IllegalStateException("nodeKind");
83 }
84 }
85
86 /**
87 * Get a {@link Processor} suitable for use with this {@link XdmNode}.
88 * <p>In most cases this will be the original {@link Processor} object used to create
89 * the {@link DocumentBuilder} that built the document that contains this node. If
90 * that {@code Processor} is not available, it will be a compatible {@code Processor},
91 * one that shares the same underlying {@link Configuration}, and hence is initialized
92 * with the same configuration settings, schema components, license features, and so on.</p>
93 * <p><i>Note: the only case where the original {@code Processor} is not available is when
94 * the same {@code Configuration} is used with multiple APIs, for example mixing s9api
95 * and JAXP or XQJ in the same application.</i></p>
96 *
97 * @return a Processor suitable for performing further operations on this node, for example
98 * for creating a {@link Serializer} or an {@link XPathCompiler}.
99 * @since 9.9
100 */
101
102 public Processor getProcessor() {
103 Configuration config = getUnderlyingNode().getConfiguration();
104 Object originator = config.getProcessor();
105 if (originator instanceof Processor) {
106 return (Processor)originator;
107 } else {
108 return new Processor(config);
109 }
110 }
111
112 /**
113 * Get the underlying implementation object representing the value. This method allows
114 * access to lower-level Saxon functionality, including classes and methods that offer
115 * no guarantee of stability across releases.
116 *
117 * @return the underlying implementation object representing the value
118 * @since 9.8 (previously inherited from XdmValue which returns a Sequence)
119 */
120 @Override
121 public NodeInfo getUnderlyingValue() {
122 return (NodeInfo) super.getUnderlyingValue();
123 }
124
125 /**
126 * Get the name of the node, as a QName
127 *
128 * @return the name of the node. In the case of unnamed nodes (for example, text and comment nodes)
129 * return null.
130 */
131
132 /*@Nullable*/
133 public QName getNodeName() {
134 NodeInfo n = getUnderlyingNode();
135 switch (n.getNodeKind()) {
136 case Type.DOCUMENT:
137 case Type.TEXT:
138 case Type.COMMENT:
139 return null;
140 case Type.PROCESSING_INSTRUCTION:
141 case Type.NAMESPACE:
142 if (n.getLocalPart().isEmpty()) {
143 return null;
144 } else {
145 return new QName(new StructuredQName("", "", n.getLocalPart()));
146 }
147 case Type.ELEMENT:
148 case Type.ATTRIBUTE:
149 return new QName(n.getPrefix(), n.getURI(), n.getLocalPart());
150 default:
151 return null;
152 }
153 }
154
155 /**
156 * Get the typed value of this node, as defined in XDM
157 *
158 * @return the typed value. If the typed value is a single atomic value, this will be returned
159 * as an instance of {@link XdmAtomicValue}
160 * @throws SaxonApiException if an error occurs obtaining the typed value, for example because
161 * the node is an element with element-only content
162 */
163
164 public XdmValue getTypedValue() throws SaxonApiException {
165 try {
166 AtomicSequence v = getUnderlyingNode().atomize();
167 return XdmValue.wrap(v);
168 } catch (XPathException e) {
169 throw new SaxonApiException(e);
170 }
171 }
172
173 /**
174 * Get the line number of the node in a source document. For a document constructed using the document
175 * builder, this is available only if the line numbering option was set when the document was built (and
176 * then only for element nodes). If the line number is not available, the value -1 is returned. Line numbers
177 * will typically be as reported by a SAX parser: this means that the line number for an element node is the
178 * line number containing the closing "&gt;" of the start tag.
179 *
180 * @return the line number of the node, or -1 if not available.
181 */
182
183 public int getLineNumber() {
184 return getUnderlyingNode().getLineNumber();
185 }
186
187 /**
188 * Get the column number of the node in a source document. For a document constructed using the document
189 * builder, this is available only if the line numbering option was set when the document was built (and
190 * then only for element nodes). If the column number is not available, the value -1 is returned. Column numbers
191 * will typically be as reported by a SAX parser: this means that the column number for an element node is the
192 * position of the closing "&gt;" of the start tag.
193 *
194 * @return the column number of the node, or -1 if not available.
195 */
196
197 public int getColumnNumber() {
198 return getUnderlyingNode().getColumnNumber();
199 }
200
201 /**
202 * Get a JAXP Source object corresponding to this node, allowing the node to be
203 * used as input to transformations or queries.
204 * <p>The Source object that is returned will generally be one that is acceptable to Saxon interfaces
205 * that expect an instance of <code>javax.xml.transform.Source</code>. However, there is no guarantee
206 * that it will be recognized by other products.</p>
207 * <p><i>In fact, the current implementation always returns an instance of
208 * <code>net.sf.saxon.om.NodeInfo</code>.</i></p>
209 *
210 * @return a Source object corresponding to this node
211 */
212
213 public Source asSource() {
214 return getUnderlyingNode();
215 }
216
217
218 /**
219 * Get the children of this node
220 * @return an {@link Iterable} containing all nodes on the child axis
221 * @since 9.9
222 */
223 public Iterable<XdmNode> children() {
224 return select(Steps.child()).asListOfNodes();
225 }
226
227 /**
228 * Get the element children of this node having a specified
229 * local name, irrespective of the namespace
230 *
231 * @param localName the local name of the child elements to be selected,
232 * or "*" to select all children that are element nodes
233 * @return an {@link Iterable} containing the element children of this node that have the
234 * required local name.
235 * @since 9.9
236 */
237
238 public Iterable<XdmNode> children(String localName) {
239 return select(Steps.child(localName)).asListOfNodes();
240 }
241
242 /**
243 * Get the element children having a specified namespace URI and local name
244 *
245 * @param uri the namespace URI of the child elements to be selected:
246 * supply a zero-length string to indicate the null namespace
247 * @param localName the local name of the child elements to be selected
248 * @return an {@link Iterable} containing the element children of this node that have the
249 * required local name and namespace URI.
250 * @since 9.9
251 */
252
253 public Iterable<XdmNode> children(String uri, String localName) {
254 return select(Steps.child(uri, localName)).asListOfNodes();
255 }
256
257 /**
258 * Get the nodes found on the child axis that satisfy a supplied {@code Predicate}.
259 *
260 * @param filter the predicate to be applied
261 * @return an {@link Iterable} containing those nodes found on the child axis that satisfy the supplied {@code Predicate}.
262 * @since 9.9
263 */
264
265 public Iterable<XdmNode> children(Predicate<? super XdmNode> filter) {
266 return select(Steps.child(filter)).asListOfNodes();
267 }
268
269 /**
270 * Get an iterator over the nodes reachable from this node via a given axis.
271 *
272 * @param axis identifies which axis is to be navigated
273 * @return an iterator over the nodes on the specified axis, starting from this node as the
274 * context node. The nodes are returned in axis order, that is, in document order for a forwards
275 * axis and in reverse document order for a reverse axis.
276 */
277
278 public XdmSequenceIterator<XdmNode> axisIterator(Axis axis) {
279 AxisIterator base = getUnderlyingNode().iterateAxis(axis.getAxisNumber());
280 return XdmSequenceIterator.ofNodes(base);
281 }
282
283 /**
284 * Get an iterator over the nodes reachable from this node via a given axis, selecting only
285 * those nodes with a specified name.
286 *
287 * @param axis identifies which axis is to be navigated
288 * @param name identifies the name of the nodes to be selected. The selected nodes will be those
289 * whose node kind is the principal node kind of the axis (that is, attributes for the attribute
290 * axis, namespaces for the namespace axis, and elements for all other axes) whose name matches
291 * the specified name.
292 * <p>For example, specify <code>new QName("", "item")</code> to select nodes with local name
293 * "item", in no namespace.</p>
294 * @return an iterator over the nodes on the specified axis, starting from this node as the
295 * context node. The nodes are returned in axis order, that is, in document order for a forwards
296 * axis and in reverse document order for a reverse axis.
297 */
298
299 public XdmSequenceIterator<XdmNode> axisIterator(Axis axis, QName name) {
300 int kind;
301 switch (axis) {
302 case ATTRIBUTE:
303 kind = Type.ATTRIBUTE;
304 break;
305 case NAMESPACE:
306 kind = Type.NAMESPACE;
307 break;
308 default:
309 kind = Type.ELEMENT;
310 break;
311 }
312 NodeInfo node = getUnderlyingNode();
313 NameTest test = new NameTest(kind, name.getNamespaceURI(), name.getLocalName(),
314 node.getConfiguration().getNamePool());
315 AxisIterator base = node.iterateAxis(axis.getAxisNumber(), test);
316 return XdmSequenceIterator.ofNodes(base);
317 }
318
319 /**
320 * Get the parent of this node
321 *
322 * @return the parent of this node (a document or element node), or null if this node has no parent.
323 */
324
325 public XdmNode getParent() {
326 NodeInfo p = getUnderlyingNode().getParent();
327 return p == null ? null : (XdmNode) XdmValue.wrap(p);
328 }
329
330 /**
331 * Get the root of the tree containing this node (which may or may not be a document node)
332 *
333 * @return the root of the tree containing this node. Returns this node itself if it has no parent.
334 * @since 9.9
335 */
336
337 public XdmNode getRoot() {
338 NodeInfo p = getUnderlyingNode().getRoot();
339 return p == null ? null : (XdmNode) XdmValue.wrap(p);
340 }
341
342 /**
343 * Get the string value of a named attribute of this element
344 *
345 * @param name the name of the required attribute
346 * @return null if this node is not an element, or if this element has no
347 * attribute with the specified name. Otherwise return the string value of the
348 * selected attribute node.
349 */
350
351 public String getAttributeValue(QName name) {
352 NodeInfo node = getUnderlyingNode();
353 return node.getAttributeValue(name.getNamespaceURI(), name.getLocalName());
354 }
355
356 /**
357 * Get the string value of a named attribute (in no namespace) of this element
358 *
359 * @param name the name of the required attribute, interpreted as a no-namespace name
360 * @return null if this node is not an element, or if this element has no
361 * attribute with the specified name. Otherwise return the string value of the
362 * selected attribute node.
363 * @since 9.9
364 */
365
366 public String attribute(String name) {
367 return getUnderlyingNode().getAttributeValue("", name);
368 }
369
370
371 /**
372 * Get the base URI of this node
373 *
374 * @return the base URI, as defined in the XDM model. The value may be null if no base URI is known for the
375 * node, for example if the tree was built from a StreamSource with no associated URI, or if the node has
376 * no parent.
377 * @throws IllegalStateException if the base URI property of the underlying node is not a valid URI.
378 */
379
380 public URI getBaseURI() {
381 try {
382 String uri = getUnderlyingNode().getBaseURI();
383 if (uri == null) {
384 return null;
385 }
386 return new URI(uri);
387 } catch (URISyntaxException e) {
388 throw new IllegalStateException("baseURI", e);
389 }
390 }
391
392 /**
393 * Get the document URI of this node.
394 *
395 * @return the document URI, as defined in the XDM model. Returns null if no document URI is known
396 * @throws IllegalStateException if the document URI property of the underlying node is not a valid URI.
397 * @since 9.1
398 */
399
400 public URI getDocumentURI() {
401 try {
402 String systemId = getUnderlyingNode().getSystemId();
403 return systemId == null || systemId.isEmpty() ? null : new URI(systemId);
404 } catch (URISyntaxException e) {
405 throw new IllegalStateException("documentURI", e);
406 }
407 }
408
409
410 /**
411 * The hashcode is such that two XdmNode instances have the same hashCode if they represent the same
412 * node. Note that the same node might be represented by different XdmNode objects, but these will
413 * compare equal.
414 *
415 * @return a hashCode representing node identity
416 */
417
418 public int hashCode() {
419 return getUnderlyingNode().hashCode();
420 }
421
422 /**
423 * The <code>equals()</code> relation between two XdmNode objects is true if they both represent the same
424 * node. That is, it corresponds to the "is" operator in XPath.
425 *
426 * @param other the object to be compared
427 * @return true if and only if the other object is an XdmNode instance representing the same node
428 */
429
430 public boolean equals(Object other) {
431 return other instanceof XdmNode &&
432 getUnderlyingNode().equals(((XdmNode) other).getUnderlyingNode());
433 }
434
435 /**
436 * The toString() method returns a simple XML serialization of the node
437 * with defaulted serialization parameters.
438 * <p>In the case of an element node, the result will be a well-formed
439 * XML document serialized as defined in the W3C XSLT/XQuery serialization specification,
440 * using options method="xml", indent="yes", omit-xml-declaration="yes".</p>
441 * <p>In the case of a document node, the result will be a well-formed
442 * XML document provided that the document node contains exactly one element child,
443 * and no text node children. In other cases it will be a well-formed external
444 * general parsed entity.</p>
445 * <p>In the case of an attribute node, the output is a string in the form
446 * <code>name="value"</code>. The name will use the original namespace prefix.</p>
447 * <p>In the case of a namespace node, the output is a string in the form of a namespace
448 * declaration, that is <code>xmlns="uri"</code> or <code>xmlns:pre="uri"</code>.</p>
449 * <p>Other nodes, such as text nodes, comments, and processing instructions, are
450 * represented as they would appear in lexical XML. Note: this means that in the case
451 * of text nodes, special characters such as <code>&amp;</code> and <code>&lt;</code>
452 * are output in escaped form. To get the unescaped string value of a text node, use
453 * {@link #getStringValue()} instead.</p>
454 * <p><i>For more control over serialization, use the {@link Serializer} class.</i></p>
455 *
456 * @return a simple XML serialization of the node. Under error conditions the method
457 * may return an error message which will always begin with the label "Error: ".
458 */
459
460 public String toString() {
461 NodeInfo node = getUnderlyingNode();
462
463 if (node.getNodeKind() == Type.ATTRIBUTE) {
464 String val = node.getStringValue()
465 .replace("&", "&amp;")
466 .replace("\"", "&quot;")
467 .replace("<", "&lt;");
468 return node.getDisplayName() + "=\"" + val + '"';
469 } else if (node.getNodeKind() == Type.NAMESPACE) {
470 String val = node.getStringValue()
471 .replace("&", "&amp;")
472 .replace("\"", "&quot;")
473 .replace("<", "&lt;");
474 String name = node.getDisplayName();
475 name = name.equals("") ? "xmlns" : "xmlns:" + name;
476 return name + "=\"" + val + '"';
477 } else if (node.getNodeKind() == Type.TEXT) {
478 return node.getStringValue()
479 .replace("&", "&amp;")
480 .replace("<", "&lt;")
481 .replace("]]>", "]]&gt;");
482 }
483
484 try {
485 return QueryResult.serialize(node).trim();
486 } catch (XPathException err) {
487 throw new IllegalStateException(err);
488 }
489 }
490
491 /**
492 * Get the underlying Saxon implementation object representing this node. This provides
493 * access to classes and methods in the Saxon implementation that may be subject to change
494 * from one release to another.
495 *
496 * @return the underlying implementation object
497 */
498
499 public NodeInfo getUnderlyingNode() {
500 return getUnderlyingValue();
501 }
502
503 /**
504 * In the case of an XdmNode that wraps a node in an external object model such as DOM, JDOM,
505 * XOM, or DOM4J, get the underlying wrapped node
506 *
507 * @return the underlying external node if there is one, or null if this is not an XdmNode that
508 * wraps such an external node
509 * @since 9.1.0.2
510 */
511
512 public Object getExternalNode() {
513 NodeInfo saxonNode = getUnderlyingNode();
514 if (saxonNode instanceof VirtualNode) {
515 Object externalNode = ((VirtualNode) saxonNode).getRealNode();
516 return externalNode instanceof NodeInfo ? null : externalNode;
517 } else {
518 return null;
519 }
520 }
521
522 public XdmSequenceIterator<XdmNode> nodeIterator() {
523 return XdmSequenceIterator.ofNode(this);
524 }
525
526 /**
527 * Get a stream comprising the items in this value
528 *
529 * @return a Stream over the items in this value
530 * @since 9.9
531 */
532 public XdmStream<XdmNode> stream() {
533 return new XdmStream<>(Stream.of(this));
534 }
535
536
537 }
538