1

i am trying to parse the XML format response from Magento for android i have response like:

XML Format response:

    <response>
<id>3</id>
<parent_id>1</parent_id>
<name>Arocos</name>
<is_active>true</is_active>
<position>2</position>
<level>1</level>
<product_count>35</product_count>
<children_data>
<item>
<id>5</id>
<parent_id>3</parent_id>
<name>DHOOP CONES</name>
<is_active>true</is_active>
<position>1</position>
<level>2</level>
<product_count>4</product_count>
<children_data/>
</item>
<item>
<id>6</id>
<parent_id>3</parent_id>
<name>SAMBRANI STEMS</name>
<is_active>true</is_active>
<position>2</position>
<level>2</level>
<product_count>2</product_count>
<children_data/>
</item>
</response>

I am trying this response to parse using XML Parser but i cant get some issues

public class XMLParser {

public XMLParser() {

}

// Retrive XML from URL
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return xml;
}

// Retrive DOM element
public Document getDomElement(String xml) {
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is);

    } catch (ParserConfigurationException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (SAXException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Error: ", e.getMessage());
        return null;
    }

    return doc;
}

// Retrive Node element
public final String getElementValue(Node elem) {
    Node child;
    if (elem != null) {
        if (elem.hasChildNodes()) {
            for (child = elem.getFirstChild(); child != null; child = child
                    .getNextSibling()) {
                if (child.getNodeType() == Node.TEXT_NODE) {
                    return child.getNodeValue();
                }
            }
        }
    }
    return "";
}

// Retrive Node Value
public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}

}

and My MainActivity:

public class MainActivity extends Activity {
    // Declare Variables
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "item";
    static String COUNTRY = "name";
    static String POPULATION = "is_active";
    static String FLAG = "flag";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadXML().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadXML extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Android XML Parse Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();

            XMLParser parser = new XMLParser();
            // Retrieve nodes from the given URL address
            String xml = parser
                    .getXmlFromUrl("http://arocos.com/index.php/rest/V1/categories/");
            // Retrive DOM element
            Document doc = parser.getDomElement(xml);

            try {
                // Identify the element tag name
                NodeList nl = doc.getElementsByTagName("item");
                for (int i = 0; i < nl.getLength(); i++) {
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    Element e = (Element) nl.item(i);

                    // adding each child node to HashMap key => value
                    map.put(RANK, parser.getValue(e, RANK));
                    map.put(COUNTRY, parser.getValue(e, COUNTRY));
                    map.put(POPULATION, parser.getValue(e, POPULATION));
                    map.put(FLAG, parser.getValue(e, FLAG));
                    // adding HashList to ArrayList
                    arraylist.add(map);
                }
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Binds the Adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

Please help me and indicate me to write a correct coding... Thanks in advance..

4
  • I would use a library like Retrofit to do this. Commented Jul 12, 2017 at 11:34
  • How to do it is there any tutorial for that Commented Jul 12, 2017 at 11:40
  • The above coding is fine for me but i cant get the <children_data>..<item> Commented Jul 12, 2017 at 12:15
  • how to get the parent node and child node in this coding please help me in that way please.. Commented Jul 12, 2017 at 12:15

2 Answers 2

4

Use XmlPullParserFactory.

XmlPullParserFactory factory;
                        try {
                            factory = XmlPullParserFactory.newInstance();
                            factory.setNamespaceAware(true);
                            XmlPullParser responseParser = factory.newPullParser();
                            responseParser.setInput(new StringReader("Your Response"));
                            int eventType = responseParser.getEventType();
                            while (eventType != XmlPullParser.END_DOCUMENT) {
                                if (eventType == XmlPullParser.TEXT) {
                                    if (responseParser.getText().equals("Your key to check")) {
                                        //Your code
                                    } else {
                                       //Your code
                                    }
                                }
                                eventType = responseParser.next();
                            }
                        } catch (XmlPullParserException | IOException e) {
                            e.printStackTrace();
                        } finally {
                           // Your code
                        }

Only condition is "You should have response in string"

Sign up to request clarification or add additional context in comments.

Comments

2

One simple way is to use Retrofit with an XML parser. Usually Retrofit is used to make request and parse JSON into Java objects. But you can specify to Retrofit to use the SimpleXmlConverterFactory.

Make sure to use it when you build your Retrofit object :

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(<url>)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();

Retrofit documentation : http://square.github.io/retrofit/

Good tutorial : http://www.vogella.com/tutorials/Retrofit/article.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.