1 19 20 29 30 package org.netbeans.modules.xml.xdm.visitor; 31 32 import java.util.Collections ; 33 import java.util.LinkedList ; 34 import java.util.List ; 35 import org.netbeans.modules.xml.xdm.nodes.Document; 36 import org.netbeans.modules.xml.xdm.nodes.Element; 37 import org.netbeans.modules.xml.xdm.nodes.Node; 38 39 43 public class PathFromRootVisitor extends ChildVisitor { 44 45 public List <Node> findPath(org.w3c.dom.Document root, org.w3c.dom.Node target) { 46 Document wroot = root instanceof Document ? (Document) root : null; 47 Node wtarget = target instanceof Node ? (Node) target : null; 48 return findPath(wroot, wtarget); 49 } 50 51 public List <Node> findPathToRootElement(org.w3c.dom.Element root, org.w3c.dom.Node target) { 52 Element wroot = root instanceof Element ? (Element) root : null; 53 Node wtarget = target instanceof Node ? (Node) target : null; 54 assert root != null && target != null; 55 56 this.target = wtarget; 57 found = false; 58 pathToTarget = null; 59 wroot.accept(this); 60 return pathToTarget; 61 } 62 63 public List <Node> findPath(Document root, Node target) { 64 assert root != null; 65 if(target == null) 67 return Collections.emptyList(); 68 this.target = target; 69 found = false; 70 pathToTarget = null; 71 root.accept(this); 72 return pathToTarget; 73 } 74 75 protected void visitNode(Node n) { 76 if(found) return; 78 if (target.getId() == n.getId()) { 79 pathToTarget = new LinkedList <Node>(); 80 pathToTarget.add(n); 81 found = true; 82 } else { 83 super.visitNode(n); 84 if(found) { 85 pathToTarget.add(n); 87 } 88 } 89 } 90 91 private boolean found; 92 private List <Node> pathToTarget; 93 private Node target; 94 } 95 | Popular Tags |