1

I am looking for some examples of using xpath in Android? Or if anyone can share their experiences. I have been struggeling to make tail or head of this problem :-(

I have a string that contains a standard xml file. I believe I need to convert that into an xml document. I have found this code which I think will do the trick:

public static Document stringToDom(String xmlSource) 
throws SAXException, ParserConfigurationException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xmlSource)));
}

Next steps Assuming the code above is OK, I need to apply xpath to get values from cat: "/animal/mammal/feline/cat"

I look at the dev doc here: http://developer.android.com/reference/javax/xml/xpath/XPath.html and also look online, but I am not sure where to start!

I have tried to use the following code:

 XPathFactory xPathFactory = XPathFactory.newInstance();
// To get an instance of the XPathFactory object itself.

XPath xPath = xPathFactory.newXPath();
// Create an instance of XPath from the factory class.

String expression = "SomeXPathExpression";
XPathExpression xPathExpression = xPath.compile(expression);
// Compile the expression to get a XPathExpression object.

Object result = xPathExpression.evaluate(xmlDocument);
// Evaluate the expression against the XML Document to get the result.

But I get "Cannot be resolved". Eclipse doesn't seem to be able to fix this import. I tried manually entering:

javax.xml.xpath.XPath

But this did not work.

Does anyone know any good source code that I can utilise, for Android platform? 1.5

1
  • FWIW your code is good for me. (using SDK 8) Good to note for someone finding this post in the future. (I was missing the xpathexpression object, and the compile step) Commented Nov 6, 2011 at 23:54

2 Answers 2

4

What version of the SDK are you using? XPath was introduced in SDK 8(2.2). If you aren't building against that version then the class doesn't exist.

Sign up to request clarification or add additional context in comments.

1 Comment

This is nearly a year late, but I hope you found SAXParser and didn't have to struggle through your XML with a regex...
0

Rpond is correct:

  • javax.xml.xpath is introduced since API level 8 (Android 2.2).
  • Android 1.5. is only API Level 3.

References

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.