Android - 使用XPath解析XML

问题描述:

首先,感谢所有在这个问题上花费一点时间的人。Android - 使用XPath解析XML

其次,对不起,我的英语(不是我的第一语言:d)。

嗯,这是我的问题。

我学习Android和我做它使用XML文件来存储一些信息的应用程序。我在创建文件时没有问题,但是尝试使用XPath读取de XML标记(DOM,XMLPullParser等只能给我带来问题)至少,我已经能够读取第一个。

让我们看看代码。

下面是XML文件的应用产生:

<dispositivo> 
    <id>111</id> 
    <nombre>Name</nombre> 
    <intervalo>300</intervalo> 
</dispositivo> 

在此可以读取XML文件中的函数:

private void leerXML() { 
    try { 
     XPathFactory factory=XPathFactory.newInstance(); 
     XPath xPath=factory.newXPath(); 

     // Introducimos XML en memoria 
     File xmlDocument = new File("/data/data/com.example.gps/files/devloc_cfg.xml"); 
     InputSource inputSource = new InputSource(new FileInputStream(xmlDocument)); 

     // Definimos expresiones para encontrar valor. 
     XPathExpression tag_id = xPath.compile("/dispositivo/id"); 
     String valor_id = tag_id.evaluate(inputSource); 

     id=valor_id; 

     XPathExpression tag_nombre = xPath.compile("/dispositivo/nombre"); 
     String valor_nombre = tag_nombre.evaluate(inputSource); 

     nombre=valor_nombre; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

该应用程序正确地获取id的值,并将其显示在屏幕(“id”和“nombre”变量分配给每个TextView),但“nombre”不起作用。

我应该改变什么? :)

感谢您的时间和帮助。这个网站相当有帮助!

PD:我一直在寻找对整个网站的响应,但没有发现任何。

您使用的是相同的输入流两次,但你使用它的第二次它已经在文件的结尾。您必须再次打开流或缓冲它,例如在ByteArrayInputStream并重新使用它。

你的情况,这样做:

inputSource = new InputSource(new FileInputStream(xmlDocument)); 

此行

XPathExpression tag_nombre = xPath.compile("/dispositivo/nombre"); 

应该帮助之前。

要知道,虽然你应该正确地关闭流。

+0

太谢谢你了!它也起作用。 – arkanos

问题是您不能重复使用流输入源多次 - 第一次调用tag_id.evaluate(inputSource)已经读取输入到最后。

一个解决办法是事先解析文档:

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
Document document = documentBuilderFactory.newDocumentBuilder().parse(inputSource); 

Source source = new DOMSource(document); 

// evalute xpath-expressions on the dom source 
+0

并且不要忘记在try-finally块中关闭输入流。 – mbelow

+0

非常感谢!有效。 – arkanos