arkanos
arkanos

Reputation: 95

Android - Parsing XML with XPath

First of all, thanks to all the people who's going to spend a little time on this question.

Second, sorry for my english (not my first language! :D).

Well, here is my problem.

I'm learning Android and I'm making an app which uses a XML file to store some info. I have no problem creating the file, but trying to read de XML tags with XPath (DOM, XMLPullParser, etc. only gave me problems) I've been able to read, at least, the first one.

Let's see the code.

Here is the XML file the app generates:

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

And here is the function which reads the XML file:

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

The app gets correctly the id value and shows it on the screen ("id" and "nombre" variables are assigned to a TextView each one), but the "nombre" is not working.

What should I change? :)

Thanks for all your time and help. This site is quite helpful!

PD: I've been searching for a response on the whole site but didn't found any.

Upvotes: 2

Views: 2561

Answers (2)

mbelow
mbelow

Reputation: 1133

The problem is that you cannot re-use the stream-input-source multiple times - the first call to tag_id.evaluate(inputSource) already has read the input up to the end.

One solution would be to parse Document in advance:

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

Source source = new DOMSource(document);

// evalute xpath-expressions on the dom source

Upvotes: 0

ShyJ
ShyJ

Reputation: 4650

You're using the same input stream twice, but the second time you use it it's already at the end of file. You have to either open the stream once more or buffer it e.g. in a ByteArrayInputStream and reuse it.

In your case doing this:

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

before this line

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

should help.

Be aware though that you should properly close your streams.

Upvotes: 2

Related Questions