如何以编程方式从android中解析XML

时间:2017-07-12 11:31:08

标签: java android xml magento

我正在尝试解析来自Magento for android的XML格式响应 我的回答如下:

XML格式响应:

    <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>

我正在尝试使用XML Parser进行解析,但我无法解决一些问题

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

}

和我的主要活动:

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

请帮帮我,并指示我写一个正确的编码...... 提前谢谢..

2 个答案:

答案 0 :(得分:4)

使用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
                        }

只有条件是“你应该在字符串中有响应”

答案 1 :(得分:2)

一种简单的方法是将Retrofit与XML解析器一起使用。通常,Retrofit用于发出请求并将JSON解析为Java对象。但您可以指定Retrofit以使用SimpleXmlConverterFactory

确保在构建Retrofit对象时使用它:

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

改造文件:http://square.github.io/retrofit/

好教程:http://www.vogella.com/tutorials/Retrofit/article.html