1 17 18 19 20 package org.apache.lenya.xml.xpointer; 21 22 import java.util.Vector ; 23 24 import org.apache.lenya.xml.DOMParserFactory; 25 import org.apache.log4j.Category; 26 import org.apache.xpath.XPathAPI; 27 import org.w3c.dom.Document ; 28 import org.w3c.dom.Element ; 29 import org.w3c.dom.Node ; 30 import org.w3c.dom.NodeList ; 31 32 33 36 public class XalanXPointer implements XPointer { 37 private static Category log = Category.getInstance(XalanXPointer.class); 38 39 44 public static void main(String [] args) { 45 XPointer xpointer = new XalanXPointer(); 46 47 if (args.length != 2) { 48 System.err.println("Usage: java " + xpointer.getClass().getName() + 49 " example.xml \"/Example/People/Person[position() < 2]/Street/@Number\""); 50 51 return; 52 } 53 54 DOMParserFactory dpf = new DOMParserFactory(); 55 Document document = null; 56 57 try { 58 document = dpf.getDocument(args[0]); 59 } catch (Exception e) { 60 System.err.println(xpointer.getClass().getName() + ".main(): " + e); 61 } 62 63 Element root = document.getDocumentElement(); 64 String xpath = args[1]; 65 66 try { 67 Vector namespaces = new Vector (); 68 Vector nodes = xpointer.select(root, xpath, namespaces); 69 70 for (int i = 0; i < nodes.size(); i++) { 71 Node node = (Node ) nodes.elementAt(i); 72 short type = node.getNodeType(); 73 74 if (type == Node.ATTRIBUTE_NODE) { 75 System.out.println("Attribute (" + node.getNodeName() + "): " + 76 node.getNodeValue()); 77 } else if (type == Node.ELEMENT_NODE) { 78 System.out.println("Element (" + node.getNodeName() + "): " + 79 node.getFirstChild().getNodeValue()); 80 } 81 } 82 } catch (Exception e) { 83 System.err.println(e); 84 } 85 } 86 87 97 public Vector select(Node node, String xpath, Vector namespaces) throws Exception { 98 NodeList children = node.getChildNodes(); 99 100 log.debug("Select " + xpath + " from node " + node.getNodeName()); 101 102 NodeList nl = null; 103 if (namespaces.size() > 0) { 104 org.w3c.dom.Document doc = org.apache.lenya.xml.DocumentHelper.createDocument("", "foo", null); 105 for (int i = 0; i < namespaces.size(); i++) { 106 String namespace = (String )namespaces.elementAt(i); 107 String prefix = namespace.substring(0, namespace.indexOf("=")); 108 String namespaceURI = namespace.substring(namespace.indexOf("=") + 1); 109 log.debug("Namespace: " + prefix + " " + namespaceURI); 110 111 doc.getDocumentElement().setAttribute("xmlns:" + prefix, namespaceURI); 112 } 113 nl = XPathAPI.selectNodeList(node, xpath, doc.getDocumentElement()); 114 } else { 115 nl = XPathAPI.selectNodeList(node, xpath); 116 } 117 118 119 if (nl != null && nl.getLength() == 0) { 120 log.info("No such nodes: " + xpath); 121 return new Vector (); 122 } 123 124 Vector nodes = new Vector (); 125 126 for (int i = 0; i < nl.getLength(); i++) { 127 nodes.addElement(nl.item(i)); 128 } 129 130 return nodes; 131 } 132 } 133 | Popular Tags |