01: package demo;
02:
03: import java.util.Iterator;
04: import org.w3c.dom.Node;
05: import org.apache.commons.jxpath.Pointer;
06: import org.enhydra.xml.xmlc.XMLObject;
07:
08: /**
09: * Demo how to set node value using XPath
10: */
11: public class Test extends XPath {
12: private String path;
13: private String value;
14: private String file;
15:
16: public Test(String f, String p, String v) {
17: file = f;
18: path = p;
19: value = v;
20: }
21:
22: public void run() {
23: XMLObject xmlObject = null;
24:
25: xmlObject = getFactory().createFromFile(file);
26: System.out.println("\nJXPath Result...");
27: runJXPath(xmlObject);
28: System.out.println(xmlObject.toDocument());
29:
30: xmlObject = getFactory().createFromFile(file);
31: System.out.println("\nJaxen Result...");
32: runJaxen(xmlObject);
33: System.out.println(xmlObject.toDocument());
34: }
35:
36: public void runJXPath(XMLObject xmlObject) {
37: for (Iterator iter = query(xmlObject, path,
38: XPath.XPATH_IMPL_JXPATH); iter.hasNext();) {
39: Pointer pointer = (Pointer) iter.next();
40:
41: System.out.println("Change " + pointer + " from '"
42: + pointer.getValue() + "' to '" + value + "'");
43: pointer.setValue(value);
44: }
45: }
46:
47: public void runJaxen(XMLObject xmlObject) {
48: for (Iterator iter = query(xmlObject, path,
49: XPath.XPATH_IMPL_JAXEN); iter.hasNext();) {
50: Node node = (Node) iter.next();
51: String nodeValue = node.getNodeValue();
52: if (nodeValue == null) {
53: node = node.getFirstChild();
54: nodeValue = node.getNodeValue();
55: }
56:
57: System.out.println("Change " + node + " from '" + nodeValue
58: + "' to '" + value + "'");
59: node.setNodeValue(value);
60: }
61: }
62:
63: public static void main(String args[]) {
64: if (args.length == 3) {
65: Test test = new Test(args[0], args[1], args[2]);
66: test.run();
67: } else {
68: System.err.println("Test file path newValue");
69: }
70: }
71:
72: }
|