从url解析xml的XmlPullparser无法正常工作

时间:2017-09-15 07:48:31

标签: java android xml inputstream xmlpullparser

我试图从xml文件填充数据库。它工作得很好,但问题是当我尝试从服务器加载xml时。 我花了好几个小时,尝试了很多不同的实现,但我总是收到异常。 这是我目前的代码:

public void populateDB(){
    XmlPullParserFactory pullParserFactory;
    ArrayList<Product> products = null;

    try {
        pullParserFactory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = pullParserFactory.newPullParser();

        InputStream in_s = fContext.getApplicationContext().getAssets().open("products.xml");

        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in_s, null);

        products =  parseXML(parser);

        String text = "";

        for(Product product:products)
        {

            text += "barcode : " + product.getBarcode() + " name : " + product.getName() + "\n";
        }

    } catch (XmlPullParserException e) {

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

    clearTable("products");
    ContentValues values = new ContentValues();
    for(int i = 0; i < products.size(); i++){
        values.clear();
        values.put("barcode", products.get(i).getBarcode());
        values.put("name", products.get(i).getName());
        values.put("itemcode", products.get(i).getItemcode());
        values.put("description", products.get(i).getDescription());

        insertProduct(values);
    }
}

这是parseXML(),我解析文件并生成产品列表。

private ArrayList<Product> parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
{
    ArrayList<Product> products = null;
    int eventType = parser.getEventType();
    Product product = null;

    while (eventType != XmlPullParser.END_DOCUMENT){
        String name;
        switch (eventType){
            case XmlPullParser.START_DOCUMENT:
                products = new ArrayList();
                break;
            case XmlPullParser.START_TAG:
                name = parser.getName();
                if (name.equals("product")){
                    product = new Product();
                } else if (product != null){
                    if (name.equals("barcode")){
                        product.setBarcode(parser.nextText());
                    } else if (name.equals("name")){
                        product.setName(parser.nextText());
                    } else if (name.equals("itemcode")){
                        product.setItemcode(Integer.parseInt(parser.nextText()));
                    } else if (name.equals("description")){
                        product.setDescription(parser.nextText());
                    }
                }
                break;
            case XmlPullParser.END_TAG:
                name = parser.getName();
                if (name.equalsIgnoreCase("product") && product != null){
                    products.add(product);
                }
        }
        eventType = parser.next();
    }

    return products;

}

现在这只适用于本地文件,但是如果我想从网址加载它? 我尝试了this主题和thisthis中给出的解决方案,  thisthis,但它仍无法正常工作。

似乎指令parser.setInput(in_s, null);不接受包含url的输入流。

xml文件路径如下:http://cendav.altervista.org/gestione_magazzino/products.xml

1 个答案:

答案 0 :(得分:1)

通常我会输入asyncTask:

class getXMLResponseAsyncTask extends AsyncTask<String, Void, Boolean>{

        @Override
        protected void onPreExecute(){
         //do something
        }


        @Override
        public Boolean doInBackground(String... urls) {
            URL url;

            try {
                url = new URL(urls[0]);

                URLConnection connection = url.openConnection();

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(connection.getInputStream());


                NodeList nodes = doc.getElementsByTagName("products");
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    NodeList barcode = element.getElementsByTagName("barcode");
                    NodeList name = element.getElementsByTagName("name");
                    NodeList itemcode = element.getElementsByTagName("itemcode");



                    Element barcodeval = (Element) barcode.item(0);
                    Element nameval = (Element) name.item(0);
                    Element itemcodeval = (Element) itemcode.item(0);



                    String BARCODE = barcodeval.getTextContent();
                    String NAME  = nameval.getTextContent();
                    String ITEMCODE = itemcodeval.getTextContent();


                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }

            return false;
        }

        public void onPostExecute(Boolean result) {
        //do something
        }
    }

最后您可以使用它而不想使用

    new getXMLResponseAsyncTask().execute("http://cendav.altervista.org/gestione_magazzino/products.xml");