KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > demo > XPath


1 package demo;
2
3 import java.util.Iterator JavaDoc;
4 import java.io.OutputStreamWriter JavaDoc;
5 import java.io.PrintWriter JavaDoc;
6
7 import org.w3c.dom.Node JavaDoc;
8 import org.w3c.dom.NodeList JavaDoc;
9 import org.w3c.dom.NamedNodeMap JavaDoc;
10
11 import org.apache.commons.jxpath.JXPathContext;
12 import org.apache.commons.jxpath.Pointer;
13
14 import org.jaxen.XPathSyntaxException;
15 import org.jaxen.JaxenException;
16 import org.jaxen.dom.html.HTMLXPath;
17
18 import org.enhydra.xml.xmlc.StreamXMLCLogger;
19 import org.enhydra.xml.xmlc.XMLObject;
20 import org.enhydra.xml.xmlc.StreamXMLCLogger;
21 import org.enhydra.xml.xmlc.deferredparsing.XMLCDeferredParsingFactory;
22
23 public class XPath
24 {
25     public static final int XPATH_IMPL_JAXEN = 0;
26     public static final int XPATH_IMPL_JXPATH = 1;
27
28     static private XMLCDeferredParsingFactory xmlcFactory = null;
29
30     protected XMLCDeferredParsingFactory getFactory() {
31     if (xmlcFactory != null) {
32         return xmlcFactory;
33     }
34
35     PrintWriter JavaDoc writer = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(System.err));
36     StreamXMLCLogger logger = new StreamXMLCLogger(writer, writer, writer);
37     xmlcFactory = new XMLCDeferredParsingFactory(null, this.getClass().getClassLoader(), null);
38     xmlcFactory.addResourceDir(".");
39     xmlcFactory.addResourceDir("./input");
40     xmlcFactory.addResourceDir("./build/src");
41     xmlcFactory.addPackagePrefix("demo");
42
43     xmlcFactory.setDefaultMetaDataPath("input/options.xmlc");
44     return xmlcFactory;
45     }
46     
47     public Iterator JavaDoc query(XMLObject xmlObject, String JavaDoc query, int xpathImpl) {
48     /* create an Iterator to hold the results of the query */
49     Iterator JavaDoc iter = new java.util.ArrayList JavaDoc().iterator(); //guarantee default non-null Iterator
50
switch (xpathImpl) {
51         case XPATH_IMPL_JAXEN:
52             try {
53                 org.jaxen.XPath xpath = new HTMLXPath(query, true);
54                 iter = xpath.selectNodes((Node JavaDoc)xmlObject).iterator();
55             }
56                 catch (XPathSyntaxException xse) {System.err.println(xse.getMultilineMessage());}
57                 catch (JaxenException je) {je.printStackTrace();}
58                 catch (Exception JavaDoc e) {e.printStackTrace();}
59             break;
60         case XPATH_IMPL_JXPATH:
61             JXPathContext context = JXPathContext.newContext(xmlObject);
62             iter = context.iteratePointers(query);
63             break;
64     }
65     return iter;
66     }
67
68     public Iterator JavaDoc query(String JavaDoc file, String JavaDoc query, int xpathImpl) {
69     /* loading the document with dyanmic loading */
70     XMLObject xmlObject = getFactory().createFromFile(file);
71     return query(xmlObject, query, xpathImpl);
72     }
73
74     public static void main(String JavaDoc[] args) {
75         System.out.println("\nJXPath Result...");
76         JXPathMain(args);
77         System.out.println("\nJaxen Result...");
78         JaxenMain(args);
79     }
80
81     public static void JXPathMain (String JavaDoc[] args) {
82     if (args.length == 2) {
83         XPath xpath = new XPath();
84         int count = 0;
85         for (Iterator JavaDoc iter = xpath.query(args[0], args[1], XPATH_IMPL_JXPATH); iter.hasNext(); count++) {
86         Pointer pointer = (Pointer)iter.next();
87         Node JavaDoc node = (Node JavaDoc)pointer.getNode();
88                 String JavaDoc nodeValue = node.getNodeValue();
89                 if (nodeValue == null) {
90                     NodeTreeGenerator ntgen = new NodeTreeGenerator();
91                     ntgen.setDoIndent(true);
92                     ntgen.makeNodeTree(node);
93                     nodeValue = ntgen.getNodeTree();
94                 }
95         //System.out.println ("Result " + count + " --- " + pointer.getNode().getClass() + " value:\n" + pointer.getValue());
96
System.out.println ("Result " + count + " --- " + node.getClass() + " value:\n" + nodeValue);
97         }
98     } else {
99         System.out.println ("xpath file query");
100     }
101     }
102
103     public static void JaxenMain (String JavaDoc[] args) {
104     if (args.length == 2) {
105         XPath xpath = new XPath();
106             int count = 0;
107             for (Iterator JavaDoc iter = xpath.query(args[0], args[1], XPATH_IMPL_JAXEN); iter.hasNext(); count++) {
108                 Node JavaDoc node = (Node JavaDoc)iter.next();
109                 String JavaDoc nodeValue = node.getNodeValue();
110                 if (nodeValue == null) {
111                     NodeTreeGenerator ntgen = new NodeTreeGenerator();
112                     ntgen.setDoIndent(true);
113                     ntgen.makeNodeTree(node);
114                     nodeValue = ntgen.getNodeTree();
115                 }
116                 System.out.println ("Result " + count + " --- " + node.getClass() + " value:\n" + nodeValue);
117             }
118     } else {
119         System.out.println ("xpath file query");
120     }
121     }
122
123
124     public static class NodeTreeGenerator {
125     
126         // a counter for keeping track of the "tabs"
127
private int tabCounter = 1;
128         private StringBuffer JavaDoc nodeTreeBuffer;
129         private boolean doIndent = true;
130     
131         public NodeTreeGenerator() {
132             nodeTreeBuffer = new StringBuffer JavaDoc(200);
133         }
134
135         public void setDoIndent(boolean idoIndent) {
136             this.doIndent = idoIndent;
137         }
138         
139         public String JavaDoc getNodeTree() {
140             return this.nodeTreeBuffer.toString();
141         }
142
143         // this is a recursive function to traverse the document tree
144
private void makeNodeTree(Node JavaDoc node) {
145             String JavaDoc content = "";
146             int type = node.getNodeType();
147     
148             // check if element
149
if (type == Node.ELEMENT_NODE) {
150                 formatTree(tabCounter);
151                 nodeTreeBuffer.append("Elt: ").append(node.getNodeName()).append("\n");
152     
153                 // check if the element has any attributes
154
if (node.hasAttributes()) {
155                     // if it does, store it in a NamedNodeMap object
156
NamedNodeMap JavaDoc attributesList = node.getAttributes();
157     
158                     // iterate through the NamedNodeMap and get the attribute names and values
159
for (int j = 0; j < attributesList.getLength(); j++) {
160                         formatTree(tabCounter);
161                         nodeTreeBuffer.append("Attr: ").append(attributesList.item(j).getNodeName()).append(" = ").append(attributesList.item(j).getNodeValue()).append("\n");
162                     }
163                 }
164             }
165             else if (type == Node.TEXT_NODE) {
166                 // check if text node and print value
167
content = node.getNodeValue();
168                 if (!content.trim().equals("")){
169                     formatTree(tabCounter);
170                     nodeTreeBuffer.append("Txt: ").append(content).append("\n");
171                 }
172             }
173             else if (type == Node.COMMENT_NODE) {
174                 // check if comment node and print value
175
content = node.getNodeValue();
176                 if (!content.trim().equals("")){
177                     formatTree(tabCounter);
178                     nodeTreeBuffer.append("Cmnt: ").append(content).append("\n");
179                 }
180             }
181     
182             // check if current node has any children
183
if (node.hasChildNodes()) {
184                 // if it does, iterate through the collection
185
NodeList JavaDoc children = node.getChildNodes();
186                 for (int i=0; i< children.getLength(); i++) {
187                     tabCounter++;
188                     // recursively call function to proceed to next level
189
makeNodeTree(children.item(i));
190                     tabCounter--;
191                 }
192             }
193         }
194     
195         // this formats the output for the generated tree
196
private void formatTree(int tabCounter) {
197             if (this.doIndent) {
198                 for (int j = 1; j < tabCounter; j++) {
199                     nodeTreeBuffer.append(" ");
200                 }
201             }
202         }
203     }
204
205 }
206
Popular Tags