1 16 19 21 import java.io.FileInputStream ; 22 import java.io.OutputStreamWriter ; 23 24 import javax.xml.parsers.DocumentBuilderFactory ; 25 import javax.xml.transform.OutputKeys ; 26 import javax.xml.transform.Transformer ; 27 import javax.xml.transform.TransformerFactory ; 28 import javax.xml.transform.dom.DOMSource ; 29 import javax.xml.transform.stream.StreamResult ; 30 31 import org.apache.xpath.XPathAPI; 32 import org.w3c.dom.Document ; 33 import org.w3c.dom.Node ; 34 import org.w3c.dom.traversal.NodeIterator; 35 import org.xml.sax.InputSource ; 36 37 48 public class ApplyXPath 49 { 50 protected String filename = null; 51 protected String xpath = null; 52 53 54 public void doMain(String [] args) 55 throws Exception 56 { 57 filename = args[0]; 58 xpath = args[1]; 59 60 if ((filename != null) && (filename.length() > 0) 61 && (xpath != null) && (xpath.length() > 0)) 62 { 63 System.out.println("Loading classes, parsing "+filename+", and setting up serializer"); 67 68 InputSource in = new InputSource (new FileInputStream (filename)); 70 DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); 71 dfactory.setNamespaceAware(true); 72 Document doc = dfactory.newDocumentBuilder().parse(in); 73 74 Transformer serializer = TransformerFactory.newInstance().newTransformer(); 76 serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 77 78 System.out.println("Querying DOM using "+xpath); 80 NodeIterator nl = XPathAPI.selectNodeIterator(doc, xpath); 81 82 System.out.println("<output>"); 84 85 Node n; 86 while ((n = nl.nextNode())!= null) 87 { 88 if (isTextNode(n)) { 89 StringBuffer sb = new StringBuffer (n.getNodeValue()); 93 for ( 94 Node nn = n.getNextSibling(); 95 isTextNode(nn); 96 nn = nn.getNextSibling() 97 ) { 98 sb.append(nn.getNodeValue()); 99 } 100 System.out.print(sb); 101 } 102 else { 103 serializer.transform(new DOMSource (n), new StreamResult (new OutputStreamWriter (System.out))); 104 } 105 System.out.println(); 106 } 107 System.out.println("</output>"); 108 } 109 else 110 { 111 System.out.println("Bad input args: " + filename + ", " + xpath); 112 } 113 } 114 115 116 static boolean isTextNode(Node n) { 117 if (n == null) 118 return false; 119 short nodeType = n.getNodeType(); 120 return nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE; 121 } 122 123 124 public static void main (String [] args) 125 throws Exception 126 { 127 if (args.length != 2) 128 { 129 System.out.println("java ApplyXPath filename.xml xpath\n" 130 + "Reads filename.xml and applies the xpath; prints the nodelist found."); 131 return; 132 } 133 134 ApplyXPath app = new ApplyXPath(); 135 app.doMain(args); 136 } 137 138 } 140
| Popular Tags
|