}
private static void build(Element parent, NodeFactory factory, Element result) {
for (int i=0; i < parent.getChildCount(); i++) {
Nodes nodes;
Node child = parent.getChild(i);
if (child instanceof Element) {
Element elem = (Element) child;
Element copy = factory.startMakingElement(
elem.getQualifiedName(), elem.getNamespaceURI());
if (copy != null) {
result.appendChild(copy);
result = copy;
appendNamespaces(elem, result);
appendAttributes(elem, factory, result);
}
build(elem, factory, result); // recurse down
if (copy == null) continue; // skip element
result = (Element) copy.getParent(); // recurse up
nodes = factory.finishMakingElement(copy);
if (nodes.size()==1 && nodes.get(0)==copy) { // same node? (common case)
continue; // optimization: no need to remove and then readd same element
}
if (result.getChildCount()-1 < 0) {
throw new XMLException("Factory has tampered with a parent pointer " +
"of ancestor-or-self in finishMakingElement()");
}
result.removeChild(result.getChildCount()-1);
} else if (child instanceof Text) {
nodes = factory.makeText(child.getValue());
} else if (child instanceof Comment) {
nodes = factory.makeComment(child.getValue());
} else if (child instanceof ProcessingInstruction) {
ProcessingInstruction pi = (ProcessingInstruction) child;
nodes = factory.makeProcessingInstruction(
pi.getTarget(), pi.getValue());
} else {