2012-11-26 133 views
2

首先,感謝所有在這個問題上花費一點時間的人。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:我一直在尋找對整個網站的響應,但沒有發現任何。

回答

2

您使用的是相同的輸入流兩次,但你使用它的第二次它已經在文件的結尾。您必須再次打開流或緩衝它,例如在ByteArrayInputStream並重新使用它。

你的情況,這樣做:

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

此行

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

應該幫助之前。

要知道,雖然你應該正確地關閉流。

+0

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

0

問題是您不能重複使用流輸入源多次 - 第一次調用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