je cherche à récupérer certains attributs déclarés dans un noeud d'un fichier XML en xpath avec DOM.
je cherche a extraire le prix correspondant à l'item ayant le code de produit 321 voila mon programme :<?xml version="1.0" encoding="ISO-8859-1"?>
<inventaire>
<produit code="1" prix="432.00" quantité= "43" />
<produit code="32" prix="32.00" quantité= "100" />
<produit code="321" prix="31.00" quantité= "200" />
</inventaire>
mais j'arrive pas a avoir le résultat merci .
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 import org.w3c.dom.*; import javax.xml.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.xpath.*; import javax.xml.namespace.*; import java.io.*; public class cherche{ 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); }catch(XPathExpressionException xpee){ xpee.printStackTrace(); } } public static void main(String[] args){ try{ DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = fabrique.newDocumentBuilder(); File xml = new File("fichier.xml"); Document document = constructeur.parse(xml); evaluerDOM(document,"//produit[@code='321']", XPathConstants.STRING); }catch(Exception e){ e.printStackTrace(); } } }
Partager