2009-05-29 48 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