Xml Parsing issue

Search This thread

MXG123

New member
May 16, 2017
1
0
Hi Folks.

I am new to android studio and object oriented programming in general so apologies if this is obvious but I cannot get my head round it. I have a small xml web server and I can connect to it and send data to it and I can also read it back and view it in the monitor. I want to do xml parsing on it but cannot get it to work.

Below is the xml server being displayed in the android monitor and is from the line "System.out.println(output);"
The response is saved from a string but I think I need it in a different format to do a pull parser on it. The program basically prints this string and then crashes. What is the best way to parse my data? Any help would be really appreciated.

<TITLE>GET test page</TITLE>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: </HEAD>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <BODY>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>LED Control</H1>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?nnn" >ON</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <a href="/?fff" >OFF</a>
05-16 20:19:50.499 13394-14092/com.example.mark.gps_to_server I/System.out: <IFRAME name=inlineframe style="display:none" >
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: </IFRAME>
05-16 20:19:50.519 13394-14092/com.example.mark.gps_to_server I/System.out: <H1>Status On Now</H1>
05-16 20:19:50.529 13394-14092/com.example.mark.gps_to_server I/System.out: <H2> test</H2>

The code:

Code:
public class HTTPRequestTask extends AsyncTask<String , Void, String > {
    @Override
    protected String doInBackground(String... args) {
        String IP = args[0];
        System.out.println(IP);
        try {
            URL url = new URL(IP);
            XmlPullParser recievedData = XmlPullParserFactory.newInstance().newPullParser();
            recievedData.setInput(url.openStream(),null);
            System.setProperty("http.keepAlive", "false");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");


            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;

            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);

            }
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(output));

            System.out.println("doc");
            System.out.println(parser);
            System.out.println("Disconnecting\n");
            conn.disconnect();
           //System.out.println(recievedData);
            processRecievedData(recievedData);

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (XmlPullParserException e) {
            e.printStackTrace();

        }

        return null;
    }




    private int processRecievedData(XmlPullParser xmlData) {
        int recordsFound = 0; // Find values in the XML records
        int eventType = -1;
        String appId = ""; // Attributes
        String itemId = "";
        String timeStamp = ""; String data = ""; // Text int eventType = -1;
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            String tagName = xmlData.getName();
            switch (eventType) {
                case XmlResourceParser.START_TAG: // Start of a record, so pull values encoded as attributes.
                     if (tagName.equals("Version")) {
                          System.out.println("yes");
                     appId = xmlData.getAttributeValue(null, "Model");
                         itemId = xmlData.getAttributeValue(null, "vendor_id");
                         timeStamp = xmlData.getAttributeValue(null, "timestamp");
                         data = "";
                     }
                    System.out.println("no");
                    break;
                // Grab data text (very simple processing)
                // NOTE: This could be full XML data to process.
                case XmlResourceParser.TEXT:
                    data += xmlData.getText();
                    break;

                case XmlPullParser.END_TAG:
                    if (tagName.equals("record")) {
                        recordsFound++;
                        //publishProgress(appId, itemId, data, timeStamp);
                    }
                    break;
            }
                     //eventType = xmlData.next();
        }
        // Handle no data available: Publish an empty event.
            if (recordsFound == 0) { publishProgress();
            }
            Log.i(TAG, "Finished processing "+recordsFound+" records.");
            return recordsFound;

    }


    protected void onProgressUpdate(String... values) {
        if (values.length == 0) {
            Log.i(TAG, "No data downloaded");
        }
        if (values.length == 4) {
            String appId = values[0];
            String itemId = values[1];
            String data = values[2];
            String timeStamp = values[3];
            // Log it
            Log.i(TAG, "AppID: " + appId + ", Timestamp: " + timeStamp);
            Log.i(TAG, " ItemID: " + itemId + ", Data: " + data);
            // Pass it to the application handleNewRecord(itemId, data); }
            //super.onProgressUpdate(values);
        }
    }

Thanks.
 

Unity Dev

Member
Dec 12, 2015
30
4
Probably you should use 3rd party library to parse XML from your web server. This will significantly reduce the code and improve performance. Of course, before parsing xml, you should download the data.
 

Groentje

Member
May 29, 2017
7
0
play.google.com
Personal prefference

I prefer the document (DOM) parsing. I think DOM parsing is more object oriented.

Whats the error in the log?

this works for me:


BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}

StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}

String sb_string = sb.toString();

Document return_doc = null;
if(sb_string.equals(0))
{

}
else {
DocumentBuilder db = null;
try {
db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(sb_string));

try {
return_doc = db.parse(is);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Please note! It took me a while before i could get attributes and knew the difference between nodes and elements.
this line of thought will require you to gain more information how to work with documents which might get frustration but in the end it might be beneficial.