Reputation: 11920
This an example of XML file:
<?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>
Si I want to search in this file by many criteria books, for example by author, by genre, price, etc...
I will use XPath queries to do this, So is there some simple method to use??? For example, I want to check if an author exist and to do this I must have a method in which I'll pass an XPath query to turn me the result...
Thanks in advance,
Best regards,
Ali
Upvotes: 1
Views: 2361
Reputation: 37944
You can combine DOM API with javax.xml.xpath.XPathFactory and javax.xml.xpath.XPath as descibed at http://developer.android.com/reference/javax/xml/xpath/package-summary.html.
For example:
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();;
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse("input.xml");
// NodeList books = document.getElementsByTagName("book");
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/catalog/book[1]/author"; // first book
Node author = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (author == null)
System.out.println("Element author not exists");
else
System.out.println(author.getTextContent());
Upvotes: 3