2009-05-29 56 views
7

SAXON XPath引擎這裏是我的代碼:在Java中使用

public static void main(String[] args) { 

    // System.setProperty(
    // "javax.xml.xpath.XPathFactory", 
    // "net.sf.saxon.xpath.XPathFactoryImpl"); 

    String xml="<root><a>#BBB#</a><a>#CCC#</a><b><a>#DDD#</a></b></root>"; 
    try{ 
     JDocument dom = new JDocument(xml); 

     XPathFactory factory = net.sf.saxon.xpath.XPathFactoryImpl.newInstance(); 
     XPath xpath = factory.newXPath(); 
     XPathExpression expr = xpath.compile("//a[matches(.,'#...#')]"); 

     Object result = expr.evaluate(dom, XPathConstants.NODESET); 
     NodeList nodes = (NodeList) result; 
     Nodes sharped = new Nodes(nodes); 

     for (Node n:sharped){ 
      System.out.println(n.toString()); 
     } 
    } 
    catch(Exception e){ 
     e.printStackTrace(); 
    } 

} 

而且我得到這個:

javax.xml.transform.TransformerException: Impossible to find the function : matches 
at org.apache.xpath.compiler.XPathParser.error(XPathParser.java:608) 
at org.apache.xpath.compiler.XPathParser.FunctionCall(XPathParser.java:1505) 
at org.apache.xpath.compiler.XPathParser.PrimaryExpr(XPathParser.java:1444) 
at org.apache.xpath.compiler.XPathParser.FilterExpr(XPathParser.java:1343) 
at org.apache.xpath.compiler.XPathParser.PathExpr(XPathParser.java:1276) 

這意味着Java的使用org.apache.xpath.compiler.XPathParser類時,我清楚地通過net.sf.saxon.xpath.XPathFactoryImpl創建我的工廠。

(我其實只需要在我的xpaths中放一些matches ...所以如果有任何解決方案不涉及撒克遜是已知的,考慮我的需要達成)。

我在做什麼錯?

回答

11

從撒克遜例子:

System.setProperty("javax.xml.xpath.XPathFactory:"+NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl"); 
XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON); 

工作正常。

+0

如果您對jar文件感到困惑,則需要將saxon核心和saxon dome添加到您的依賴項以使其工作,否則您將得到一個「」無法找到com類節點的對象模型實現。 sun.org.apache.xerces.internal.dom.DeferredDocumentImpl「異常 – Arash 2011-10-05 18:31:03