Skip to content

Instantly share code, notes, and snippets.

@enebo
Last active December 20, 2015 09:19
Show Gist options
  • Save enebo/6106691 to your computer and use it in GitHub Desktop.
Save enebo/6106691 to your computer and use it in GitHub Desktop.
private static Node find(Node oldRoot, Node oldObject, Node newRoot) {
// Walk down the tree to locate oldObject, and in the process, pick the same child for newRoot
List<?extends Node> oldChildren = oldRoot.childNodes();
List<?extends Node> newChildren = newRoot.childNodes();
Iterator<?extends Node> itOld = oldChildren.iterator();
Iterator<?extends Node> itNew = newChildren.iterator();
while (itOld.hasNext()) {
if (!itNew.hasNext()) {
return null; // No match - the trees have changed structure
}
Node o = itOld.next();
Node n = itNew.next();
if (o == oldObject) {
// Found it!
return n;
}
// Recurse
Node match = find(o, oldObject, n);
if (match != null) {
return match;
}
}
if (itNew.hasNext()) {
return null; // No match - the trees have changed structure
}
return null;
}
private static Node find(Node oldRoot, Node oldObject, Node newRoot) {
// Walk down the tree to locate oldObject, and in the process, pick the same child for newRoot
Iterator<Node> itNew = newRoot.childNodes().iterator();
for (Node o: oldRoot.childNodes()) {
if (!itNew.hasNext()) return null; // different number of nodes between trees. mismatch
if (o == oldObject) return itNew.next(); // found location in old tree return new equiv.
Node match = find(o, oldObject, itNew.next()); // depth-first search
if (match != null) return match;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment