Question

I'm testing Xmlpull, I've actually parsed xml locally on my computer. Now, I would like to parse an XML file on internet, the file is:

http://api.androidhive.info/pizza/?format=xml

but I can't find a way to stream data to the XmlPullParser object, please give me some general guideline on how to solve this?

An other approach I thought, was to download the xml file via java io and then parse the file locally, but this is not exactly what I was trying to achieve. I would like to parse the xml file directly on on internet, without storing a copy locally.

anyways please tell me the best practice.

Thanks, hope everything is clear

Was it helpful?

Solution

Presumably your intent is to do that with Android APIs, so please translate as appropriate.

In plain Java, there is XmlStreamReader for StAX parsing, and it can be instantiated with an InputStream from an URLConnnection, like this:

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class ParseStream {

  public static void main(String[] args) throws Exception {
    URLConnection connection =
      new URL("http://api.androidhive.info/pizza/?format=xml").openConnection();
    InputStream inputStream = connection.getInputStream();
    XMLStreamReader streamReader =
      XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "UTF-8");
    while (streamReader.hasNext())
      if (streamReader.next() == XMLStreamConstants.START_ELEMENT)
        System.out.println("START_ELEMENT " + streamReader.getName());
  }
}

In fact I would refine it somewhat, e.g. get the encoding out of the URLConnection rather than using a fixed one.

But it should give the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top