1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.backsource.utils.xml;
21 import java.io.File;
22 import java.util.List;
23 import java.util.Iterator;
24
25 import org.w3c.dom.Node;
26 import org.w3c.dom.Document;
27 import org.jaxen.XPath;
28 import org.jaxen.JaxenException;
29 import org.jaxen.dom.DOMXPath;
30 /***
31 * Util to make it easy to get nodes from a document with the help of an XPath expression.
32 *
33 *
34 * @author <a href="mailto:pra@tim.se">Peter Antman</a>
35 * @version $Revision: 1.1.1.1 $
36 */
37
38 public class XPathUtil{
39 private XPathUtil (){
40
41 }
42
43 /***
44 * Get the DOM specifix XPath engine.
45 */
46 protected static XPath getDOMXPath(String xpath)throws XmlException {
47
48 try {
49 return new DOMXPath(xpath);
50 } catch (JaxenException e) {
51 throw new XmlException("Could not construct DOM XPath:" + e,e);
52 }
53 }
54
55
56 /***
57 * <p>Select a single node from node based on xpath.
58 *
59 * @returns a single node even if the xpath hits more than one node. Returns null if no node was hitted.
60 */
61 public static Node selectSingleNode(Node xml, String xpath) throws XmlException {
62 try {
63 return (Node)getDOMXPath(xpath).selectSingleNode(xml);
64 } catch (JaxenException e) {
65 throw new XmlException("Could not select single node:" + e,e);
66 }
67 }
68
69
70 /***
71 * <p>Select all nodes from node based on xpath.
72 *
73 * @returns the number of nodes the xpath hits.
74 */
75 public static List selectNodes(Node xml, String xpath)throws XmlException {
76 try {
77 return getDOMXPath(xpath).selectNodes(xml);
78 } catch (JaxenException e) {
79 throw new XmlException("Could not select nodes:" + e,e);
80 }
81 }
82
83
84 public static void main(String[] args){
85 if ( args.length < 2) {
86 System.out.println("XPathUtil file.xml XPATHEXPR");
87 System.exit(0);
88 }
89 try {
90 String file = args[0];
91 String xpath = args[1];
92
93 Document doc = DocumentUtil.getDocument( new File(file) );
94
95
96
97
98 Iterator nodes = selectNodes(doc,xpath).iterator();
99 while ( nodes.hasNext()) {
100 Object o = nodes.next();
101
102 if ( o instanceof Node) {
103 System.out.println("Found node:" + DocumentUtil.getXml( (Node)o, true,null,true));
104 } else {
105 System.out.println("Found " + o +" ( " + o.getClass() +")");
106
107 }
108
109 }
110
111 } catch (Exception e) {
112 System.out.println("Could not run xpath " + e);
113 e.printStackTrace();
114 }
115
116 }
117 }