2011-04-01 2 views
7

Je développe une application sur android! Eh bien, j'ai un peu de conflit maintenant, je veux exécuter une requête XPath mais je ne suis pas arrivé à résoudre ce problème.Rechercher dans le fichier XML avec XPath dans Android

enter image description here

Cet exemple de XML filethat J'utilise:

<?xml version="1.0"?> 
<catalog> 
    <book id="bk101"> 
    <author>Gambardella, Matthew</author> 
<title>XML Developer's Guide</title> 
<genre>Computer</genre> 
<price>44.95</price> 
<publish_date>2000-10-01</publish_date> 
<description>An in-depth look at creating applications 
    with XML.</description> 
</book> 

<book id="bk102"> 
<author>Ralls, Kim</author> 
<title>Midnight Rain</title> 
<genre>Fantasy</genre> 
<price>5.95</price> 
<publish_date>2000-12-16</publish_date> 
<description>A former architect battles corporate zombies, 
    an evil sorceress.</description> 
</book> 

<book id="bk103"> 
<author>Corets, Eva</author> 
<title>Maeve Ascendant</title> 
<genre>Fantasy</genre> 
<price>5.95</price> 
<publish_date>2000-11-17</publish_date> 
<description>After the collapse of a nanotechnology 
    society in England.</description> 
</book> 
</catalog> 

Comment puis-je faire ??

Merci d'avance !!

Répondre

20

Regardez cet exemple:

import java.io.FileReader; 
import javax.xml.xpath.XPath; 
import javax.xml.xpath.XPathConstants; 
import javax.xml.xpath.XPathFactory; 
import org.w3c.dom.Element; 
import org.w3c.dom.NodeList; 
import org.xml.sax.InputSource; 
public class GuestList { 
    public static void main(String[] args) throws Exception { 
    XPathFactory factory = XPathFactory.newInstance(); 
    XPath xPath = factory.newXPath(); 
    NodeList shows = (NodeList) xPath.evaluate("/schedule/show", new InputSource(new FileReader(
     "tds.xml")), XPathConstants.NODESET); 
    for (int i = 0; i < shows.getLength(); i++) { 
     Element show = (Element) shows.item(i); 
     String guestName = xPath.evaluate("guest/name", show); 
     String guestCredit = xPath.evaluate("guest/credit", show); 
     System.out.println(show.getAttribute("weekday") + ", " + show.getAttribute("date") + " - " 
      + guestName + " (" + guestCredit + ")"); 
    } 
    } 
} 

Le reste des exemples sont ici: http://jexp.ru/index.php/Java_Tutorial/XML/XPath

+2

+1 juste pour être quelqu'un qui se souvient de montrer les espaces de noms importés! – SteveCav

+0

et si j'ai le XML hébergé en ligne, je peux l'analyser, dois-je tout lire – AMH

+2

Pour lire un fichier XML externe, vous pouvez utiliser la classe URL pour ouvrir un flux en utilisant SAX. Remplacez l'instanciation show NodeList par cette ligne 'NodeList shows = (NodeList) xPath.evaluate ("/schedule/show ", nouvelle InputSource (nouvelle URL ( " http://www.exple.com/file.xml").openStream()), XPathConstants.NODESET); ' – alibenmessaoud

Questions connexes