use of org.exist.dom.INodeHandle in project exist by eXist-db.
the class Expand method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
if (args[0].isEmpty()) {
return Sequence.EMPTY_SEQUENCE;
}
// apply serialization options set on the XQuery context
final Properties serializeOptions = new Properties();
serializeOptions.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes");
serializeOptions.setProperty(EXistOutputKeys.HIGHLIGHT_MATCHES, "elements");
if (getArgumentCount() == 2) {
final String serOpts = args[1].getStringValue();
final String[] contents = Option.tokenize(serOpts);
for (String content : contents) {
final String[] pair = Option.parseKeyValuePair(content);
if (pair == null) {
throw new XPathException(this, "Found invalid serialization option: " + content);
}
logger.debug("Setting serialization property: {} = {}", pair[0], pair[1]);
serializeOptions.setProperty(pair[0], pair[1]);
}
} else {
context.checkOptions(serializeOptions);
}
context.pushDocumentContext();
try {
final InMemoryNodeSet result = new InMemoryNodeSet();
final MemTreeBuilder builder = new MemTreeBuilder(getContext());
final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
int attrNr = -1;
for (final SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
final NodeValue next = (NodeValue) i.nextItem();
final short nodeType = ((INodeHandle) next).getNodeType();
builder.startDocument();
if (nodeType == Node.ATTRIBUTE_NODE) {
// NOTE: Attributes nodes need special handling as they cannot be directly serialized via SAX to a ContentHandler
final Attr attr = (Attr) next.getNode();
String ns = attr.getNamespaceURI();
if (ns == null || ns.isEmpty()) {
ns = XMLConstants.NULL_NS_URI;
}
attrNr = builder.addAttribute(new QName(attr.getLocalName(), ns), attr.getValue());
} else {
next.toSAX(context.getBroker(), receiver, serializeOptions);
}
builder.endDocument();
if (Node.DOCUMENT_NODE == nodeType) {
result.add(builder.getDocument());
} else if (Node.ATTRIBUTE_NODE == nodeType) {
result.add(builder.getDocument().getAttribute(attrNr));
} else {
result.add(builder.getDocument().getNode(1));
}
builder.reset(getContext());
}
return result;
} catch (final SAXException e) {
throw new XPathException(this, e);
} finally {
context.popDocumentContext();
}
}
Aggregations