简体   繁体   中英

Parsing xml in Android without xml declaration using SAX

Here's the XML I'm trying to parse: http://realtime.catabus.com/InfoPoint/rest/routes/get/51

 @Override
    protected Void doInBackground(String... Url) {
        try {
            URL url = new URL(Url[0]);
            DocumentBuilderFactory dbf = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            // Download the XML file
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();
            // Locate the Tag Name
            nodelist = doc.getElementsByTagName("VehicleLocation");

        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;

    }

During runtime, when it reaches this line: DocumentBuilder db = dbf.newDocumentBuilder(); I get the following error:

Unexpected token (position:TEXT {"RouteId":51,"R...@1:1298 in java.io.InputStreamReader@850b9be) 

It seems to have something to do with the encoding. My guess is that it's because the XML doesn't sepcify the encoding, but maybe not.

Is there a way to specify the encoding in the code (I can't change the XML itself)?

Thanks!

EDIT: This seems to only happen when parsing the XML from the url. Storing the file locally seems to work fine.

Is there a way to specify the encoding in the code (I can't change the XML itself)?

You can call InputSource.setEncoding() to set the encoding.

I would suggest to take a look at XmlPullParser instead for parsing XML in Android.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM