1 19 20 package edu.umd.cs.findbugs.xml; 21 22 import java.util.Iterator ; 23 import java.util.List ; 24 25 import org.dom4j.Attribute; 26 import org.dom4j.Document; 27 import org.dom4j.Element; 28 import org.dom4j.Node; 29 import org.dom4j.io.SAXReader; 30 31 44 public abstract class XPathFind { 45 private Document document; 46 47 public XPathFind(Document document) { 48 this.document = document; 49 } 50 51 public void find(String xpath) { 52 for (Node node : (List <Node>) document.selectNodes(xpath)) { 53 match(node); 54 } 55 } 56 57 protected abstract void match(Node node); 58 59 public static void main(String [] argv) throws Exception { 60 if (argv.length != 2) { 61 System.err.println("Usage: " + XPathFind.class.getName() + 62 ": <filename> <xpath expression>"); 63 System.exit(1); 64 } 65 66 String fileName = argv[0]; 67 String xpath = argv[1]; 68 69 SAXReader reader = new SAXReader(); 70 Document document = reader.read(fileName); 71 72 XPathFind finder = new XPathFind(document) { 73 @Override 74 protected void match(Node node) { 75 if (node instanceof Element) { 77 Element element = (Element) node; 78 System.out.println("Element: " + element.getQualifiedName()); 79 System.out.println("\tText: " + element.getText()); 80 System.out.println("\tAttributes:"); 81 for (Iterator <Attribute> i = element.attributeIterator(); i.hasNext(); ) { 82 Attribute attribute = i.next(); 83 System.out.println("\t\t" + attribute.getName() + "=" + attribute.getValue()); 84 } 85 } else if (node instanceof Attribute) { 86 Attribute attribute = (Attribute) node; 87 System.out.println("Attribute: " + attribute.getName() + "=" + attribute.getValue()); 88 } 89 } 90 }; 91 92 finder.find(xpath); 93 } 94 } 95 96 | Popular Tags |