}
TreeWriter tree = new TreeWriter(runtime);
tree.startDocument(doc.getBaseURI());
XdmSequenceIterator iter = doc.axisIterator(Axis.CHILD);
XdmNode child = (XdmNode) iter.next();
while (child.getNodeKind() != XdmNodeKind.ELEMENT) {
tree.addSubtree(child);
child = (XdmNode) iter.next();
}
tree.addStartElement(child);
tree.addAttributes(child);
tree.startContent();
if ("text/html".equals(contentType)) {
XdmNode tagDoc = null;
if ("tagsoup".equals(runtime.htmlParser())) {
tagDoc = tagSoup(escapedContent);
} else {
tagDoc = parseHTML(escapedContent);
}
if (namespace == null) {
tree.addSubtree(tagDoc);
} else {
remapDefaultNamespace(tree, tagDoc);
}
} else if ("application/json".equals(contentType) || "text/json".equals(contentType)) {
JSONTokener jt = new JSONTokener(escapedContent);
XdmNode jsonDoc = JSONtoXML.convert(runtime.getProcessor(), jt, runtime.jsonFlavor());
tree.addSubtree(jsonDoc);
} else if (!"application/xml".equals(contentType)) {
throw XProcException.stepError(51);
} else {
// Put a wrapper around it so that it doesn't have to have a single root...
escapedContent = "<wrapper>" + escapedContent + "</wrapper>";
StringReader sr = new StringReader(escapedContent);
// Make sure the nodes in the unescapedContent get the right base URI
InputSource is = new InputSource(sr);
is.setSystemId(doc.getBaseURI().toASCIIString());
XdmNode unesc = runtime.parse(is);
// Now ignore the wrapper that we added...
XdmNode dummyWrapper = S9apiUtils.getDocumentElement(unesc);
XdmSequenceIterator realNodes = dummyWrapper.axisIterator(Axis.CHILD);
while (realNodes.hasNext()) {
unesc = (XdmNode) realNodes.next();
if (namespace == null) {
tree.addSubtree(unesc);
} else {
remapDefaultNamespace(tree, unesc);
}