1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.sax.*;
import javax.xml.xpath.*;
import javax.xml.namespace.*;
import java.io.*;
public class ExempleXPath{
public static void evaluerDOM(Document document, String expression, QName retour){
try{
//création du XPath
XPathFactory fabrique = XPathFactory.newInstance();
XPath xpath = fabrique.newXPath();
//évaluation de l'expression XPath
XPathExpression exp = xpath.compile(expression);
//Object resultat = exp.evaluate(document,retour);
//System.out.println(resultat);
NodeList liste = (NodeList) exp.evaluate(document,retour);
if(liste != null){
System.out.println("il y a " + liste.getLength() + " noeud(s) à afficher...");
for(int i=0; i<liste.getLength(); i++){
Node node = liste.item(i);
//if (node.hasChildNodes)
System.out.println("<" + node.getNodeName() + ">" + node.getTextContent() + "</" + node.getNodeName() + ">");
}
}
}catch(XPathExpressionException xpee){
xpee.printStackTrace();
}
}
public static void evaluerSAX(File fichier, String expression, QName retour){
try{
//création de la source
InputSource source = new InputSource(new FileInputStream(fichier));
//création du XPath
XPathFactory fabrique = XPathFactory.newInstance();
XPath xpath = fabrique.newXPath();
//évaluation de l'expression XPath
XPathExpression exp = xpath.compile(expression);
Object resultat = exp.evaluate(source,retour);
System.out.println(resultat);
}catch(XPathExpressionException xpee){
xpee.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
public static void main(String[] args){
try{
DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
DocumentBuilder constructeur = fabrique.newDocumentBuilder();
File xml = new File("test.xml");
Document document = constructeur.parse(xml);
evaluerDOM(document, "/titi", XPathConstants.NODESET);
}catch(Exception e){
e.printStackTrace();
}
/*try{
File xml = new File("Ged/fichier.xml");
evaluerSAX(xml, "//toto[@id='1']", XPathConstants.STRING);
}catch(Exception e){
e.printStackTrace();
}*/
}
} |
Partager