|
Découvrir XPath
|
Voici la classe permettant d'évaluer un document XML grâce à une expression:
import java.io.File; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.*; import org.w3c.dom.Document; import org.w3c.dom.NodeList;
public class XMLView {
private Document document; private DocumentBuilder constructeur; private String cheminFichierXml = "src/ConfigBoutons.xml"; public static Object 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);
return resultat; } catch (XPathExpressionException xpee) { xpee.printStackTrace(); } return null; } public XMLView() { try { DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance(); constructeur = fabrique.newDocumentBuilder();
//Chemin vers le fichier xml File xml = new File(cheminFichierXml); this.document = constructeur.parse(xml); //Récupération d'objets de type node NodeList list = (NodeList)evaluerDOM(document,"Boutons/bouton",XPathConstants.NODESET); //Affichage de la valeur trouvée String value = list.item(0).getAttributes().getNamedItem("image").toString(); System.out.println("Valeur de l'attribut image dans une balise bouton :"+value); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new XMLView(); } } |
Et voila le fichier xml correspondant:
ConfigBoutons.xml
<Boutons> <bouton nom="Cartes/CarteFrance" image="im1.PNG"></bouton> <bouton nom="Cartes/CarteMartinique" image="im2.PNG"></bouton> <bouton nom="Cartes/CarteOxford" image="im3.PNG"></bouton> <bouton nom="Cartes/CarteReunion" image="im4.PNG"></bouton> </Boutons>
|
|
|
|