1 19 20 package org.netbeans.modules.xml.schema.model.visitor; 21 22 import org.netbeans.modules.xml.schema.model.Schema; 23 import org.netbeans.modules.xml.schema.model.SchemaComponent; 24 import org.netbeans.modules.xml.schema.model.impl.SchemaComponentImpl; 25 import org.netbeans.modules.xml.schema.model.impl.SchemaModelImpl; 26 import org.w3c.dom.Document ; 27 import org.w3c.dom.Node ; 28 import org.w3c.dom.Element ; 29 30 34 public class FindSchemaComponentFromDOM extends DeepSchemaVisitor { 35 36 37 public FindSchemaComponentFromDOM() { 38 } 39 40 public static <T extends SchemaComponent> T find(Class <T> type, SchemaComponent root, String xpath) { 41 SchemaComponent ret = new FindSchemaComponentFromDOM().findComponent(root, xpath); 42 return type.cast(ret); 43 } 44 45 public SchemaComponent findComponent(SchemaComponent root, Element xmlNode) { 46 assert root instanceof Schema; 47 assert xmlNode != null; 48 49 this.xmlNode = xmlNode; 50 result = null; 51 root.accept(this); 52 return result; 53 } 54 55 public SchemaComponent findComponent(SchemaComponent root, String xpath) { 56 Document doc = getDocument(root); 57 if (doc == null) { 58 return null; 59 } 60 61 Node result = ((SchemaModelImpl)root.getModel()).getAccess().findNode(doc, xpath); 62 if (result instanceof Element ) { 63 return findComponent(root, (Element ) result); 64 } else { 65 return null; 66 } 67 } 68 69 private Document getDocument(SchemaComponent root) { 70 return (Document )root.getModel().getDocument(); 71 } 72 73 private Element getElement(SchemaComponent c) { 74 return (Element ) c.getPeer(); 75 } 76 77 public String getXPathForComponent(SchemaComponent root, SchemaComponent target) { 78 Document doc = getDocument(root); 79 Element element = getElement(target); 80 if (doc == null || element == null) { 81 return null; 82 } 83 return ((SchemaModelImpl)root.getModel()).getAccess().getXPath(doc, element); 84 } 85 86 protected void visitChildren(SchemaComponent component) { 87 if(result != null) return; 88 if (component.referencesSameNode(xmlNode)) { 89 result = component; 90 } else { 91 super.visitChildren(component); 92 } 93 } 94 95 private SchemaComponent result; 96 private Element xmlNode; 97 98 } 99 | Popular Tags |