2009-05-29 11 views
7

Ecco il mio codice:Utilizzando il motore SAXON Xpath in 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(); 
    } 

} 

e ottengo questo:

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) 

Il che significa che Java utilizza org.apache.xpath.compiler.XPathParser classe quando ho chiaramente creato la mia fabbrica attraverso net.sf.saxon.xpath.XPathFactoryImpl.

(In realtà ho solo bisogno di inserire un po 'di matches nei miei xpath ... quindi se qualsiasi soluzione che non coinvolge Saxon è nota, considera il mio bisogno raggiunto).

Cosa sto sbagliando?

risposta

11

Da esempi Saxon:

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

funziona bene.

+0

Se si è confusi sui file jar, è necessario aggiungere il core saxon e il saxon dome alle dipendenze per farlo funzionare, oppure si otterrà un "" Impossibile individuare un'implementazione del modello a oggetti per i nodi di classe com. sun.org.apache.xerces.internal.dom.DeferredDocumentImpl "Eccezione – Arash

+0

Come faccio il contrario, cioè forzarlo a usare l'XPathFactory predefinito nella JVM (invece di Saxon)? –

+0

No James, perché vogliamo utilizzare le funzioni XPath 2.0 come "partite" qui. – Donatello