return tree.getResult();
}
private static void removeNamespacesWriter(TreeWriter tree, XdmNode node, HashSet<String> excludeNS, boolean preserveUsed) {
if (node.getNodeKind() == XdmNodeKind.DOCUMENT) {
XdmSequenceIterator iter = node.axisIterator(Axis.CHILD);
while (iter.hasNext()) {
XdmNode cnode = (XdmNode) iter.next();
removeNamespacesWriter(tree, cnode, excludeNS, preserveUsed);
}
} else if (node.getNodeKind() == XdmNodeKind.ELEMENT) {
boolean usesDefaultNS = ("".equals(node.getNodeName().getPrefix())
&& !"".equals(node.getNodeName().getNamespaceURI()));
NodeInfo inode = node.getUnderlyingNode();
int nscount = 0;
Iterator<NamespaceBinding> nsiter = NamespaceIterator.iterateNamespaces(inode);
while (nsiter.hasNext()) {
nscount++;
nsiter.next();
}
boolean excludeDefault = false;
boolean changed = false;
NamespaceBinding newNS[] = null;
if (nscount > 0) {
newNS = new NamespaceBinding[nscount];
int newpos = 0;
nsiter = NamespaceIterator.iterateNamespaces(inode);
while (nsiter.hasNext()) {
NamespaceBinding ns = nsiter.next();
String pfx = ns.getPrefix();
String uri = ns.getURI();
boolean delete = excludeNS.contains(uri);
excludeDefault = excludeDefault || ("".equals(pfx) && delete);
// You can't exclude the default namespace if it's in use
if ("".equals(pfx) && usesDefaultNS && preserveUsed) {
delete = false;
}
changed = changed || delete;
if (!delete) {
newNS[newpos++] = ns;
}
}
NamespaceBinding onlyNewNS[] = new NamespaceBinding[newpos];
for (int pos = 0; pos < newpos; pos++) {
onlyNewNS[pos] = newNS[pos];
}
newNS = onlyNewNS;
}
NodeName newName = new NameOfNode(inode);
if (!preserveUsed) {
NamespaceBinding binding = newName.getNamespaceBinding();
if (excludeNS.contains(binding.getURI())) {
newName = new FingerprintedQName("", "", newName.getLocalPart());
}
}
tree.addStartElement(newName, inode.getSchemaType(), newNS);
if (!preserveUsed) {
// In this case, we may need to change some attributes too
XdmSequenceIterator attriter = node.axisIterator(Axis.ATTRIBUTE);
while (attriter.hasNext()) {
XdmNode attr = (XdmNode) attriter.next();
String attrns = attr.getNodeName().getNamespaceURI();
if (excludeNS.contains(attrns)) {
tree.addAttribute(new QName(attr.getNodeName().getLocalName()), attr.getStringValue());
} else {
tree.addAttribute(attr);
}
}
} else {
tree.addAttributes(node);
}
XdmSequenceIterator iter = node.axisIterator(Axis.CHILD);
while (iter.hasNext()) {
XdmNode cnode = (XdmNode) iter.next();
removeNamespacesWriter(tree, cnode, excludeNS, preserveUsed);
}
tree.addEndElement();
} else {
tree.addSubtree(node);