簡體   English   中英

Android - 使用 XPath 解析 XML

[英]Android - Parsing XML with XPath

首先,感謝所有願意花一點時間討論這個問題的人。

其次,對不起我的英語(不是我的母語!:D)。

嗯,這是我的問題。

我正在學習 Android 並且我正在制作一個使用 XML 文件來存儲一些信息的應用程序。 我在創建文件時沒有問題,但是嘗試使用 XPath(DOM、XMLPullParser 等只會給我帶來問題)讀取 XML 標記時,我至少能夠讀取第一個。

讓我們看看代碼。

這是應用程序生成的 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");

應該有幫助。

請注意,您應該正確關閉流。

問題是您不能多次重復使用流輸入源 - 對tag_id.evaluate(inputSource)的第一次調用已經讀取輸入到最后。

一種解決方案是提前解析 Document:

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

Source source = new DOMSource(document);

// evalute xpath-expressions on the dom source

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM