Search in XML File with XPath in Android
Asked Answered
S

1

8

I'm developping an application on android!

Well I have a little conflict now, I want to execute an XPath query but I didn't arrive to solve this problem.

enter image description here

This an example of XML filethat I use:

 <?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>

How can I do??

Thanks in advance!!

Struve answered 1/4, 2011 at 23:2 Comment(0)
S
24

Look at this example:

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 + ")");
    }
  }

}

The rest of examples are here : http://jexp.ru/index.php/Java_Tutorial/XML/XPath

Struve answered 14/4, 2011 at 14:3 Comment(3)
+1 just for being someone who remembers to show the imported namespaces!Pupa
what if I have the XML hosted online , I can parse it , shall I read it allHorney
To read an external XML file you can use URL class to open a stream using SAX. Replace show NodeList instantiation by this line NodeList shows = (NodeList) xPath.evaluate("/schedule/show", new InputSource(new URL( "http://www.exple.com/file.xml").openStream()), XPathConstants.NODESET);Struve

© 2022 - 2024 — McMap. All rights reserved.