} finally {
context.popDocumentContext();
}
// create the output
final MemTreeBuilder builder = context.getDocumentBuilder();
final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
receiver.checkNS = true;
try {
final SequenceIterator i = result.iterate();
Item next = i.nextItem();
StringBuilder buf = null;
boolean allowAttribs = true;
while (next != null) {
context.proceed(this, builder);
// if item is an atomic value, collect the string values of all
// following atomic values and separate them by a space.
if (Type.subTypeOf(next.getType(), Type.ATOMIC)) {
if (buf == null)
{buf = new StringBuilder();}
else if (buf.length() > 0)
{buf.append(' ');}
buf.append(next.getStringValue());
allowAttribs = false;
next = i.nextItem();
//If the item is a node, flush any collected character data and
//copy the node to the target doc.
} else if (Type.subTypeOf(next.getType(), Type.NODE)) {
//It is possible for a text node constructor to construct a text node containing a zero-length string.
//However, if used in the content of a constructed element or document node,
//such a text node will be deleted or merged with another text node.
if (next instanceof TextImpl && ((TextImpl)next).getStringValue().isEmpty()) {
next = i.nextItem();
continue;
}
if (buf != null && buf.length() > 0) {
receiver.characters(buf);
buf.setLength(0);
}
if (next.getType() == Type.ATTRIBUTE && !allowAttribs)
{throw new XPathException(this, ErrorCodes.XQTY0024,
"An attribute may not appear after another child node.");}
next.copyTo(context.getBroker(), receiver);
allowAttribs = next.getType() == Type.ATTRIBUTE || next.getType() == Type.NAMESPACE;
next = i.nextItem();
}
}
// flush remaining character data
if (buf != null && buf.length() > 0)
{receiver.characters(buf);}
} catch (final SAXException e) {
LOG.warn("SAXException during serialization: " + e.getMessage(), e);
throw new XPathException(this, e);
}
if (context.getProfiler().isEnabled())