在Android中使用字符串上的XPath(JAVA)

时间:2010-06-04 15:38:09

标签: java xml android xpath

我正在寻找在Android中使用xpath的一些示例?或者如果有人可以分享他们的经验。我一直在努力制造这个问题的尾巴或头: - (

我有一个包含标准xml文件的字符串。我相信我需要将其转换为xml文档。我发现这个代码我认为可以解决这个问题:

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

后续步骤 假设上面的代码没问题,我需要应用xpath来获取cat的值:“/ animal / mammal / feline / cat”

我在这里查看开发文档:http://developer.android.com/reference/javax/xml/xpath/XPath.html并在线查看,但我不知道从哪里开始!

我尝试使用以下代码:

 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.

但我得到“无法解决”。 Eclipse似乎无法修复此导入。我试着手动输入:

javax.xml.xpath.XPath

但这不起作用。

对于Android平台,有谁知道我可以使用的任何好的源代码? 1.5

2 个答案:

答案 0 :(得分:4)

您使用的是哪个版本的SDK? XPath是在SDK 8(2.2)中引入的。如果您不是针对该版本构建,则该类不存在。

答案 1 :(得分:0)

Rpond是正确的:

  • javax.xml.xpath是从API级别8(Android 2.2)开始引入的。
  • Android 1.5。仅限API级别3。

参考