在列表视图android中加载本地XML数据 [英] Load local xml data in listview in android

查看:140
本文介绍了在列表视图android中加载本地XML数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能提出一个简单的例子来加载本地XML数据的列表视图。

can you suggest a simple example to load local XML data in List view.

推荐答案

首先把你的XML文件到原始文件夹,然后点击下面code使用DOM解析器解析这个XML文件。

First Put your XML file into raw folder and then Use below code for parse this XML file using Dom Parser.

public class XMLParsingDOMExample extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Create a new layout to display the view */
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(1);

        /** Create a new textview array to display the results */
        TextView id[];
        TextView imageurl[];

        try {

            InputStream is = res.openRawResource(R.raw.localxmlfileName);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(is));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("item");

            /** Assign textview array lenght by arraylist size */
            id = new TextView[nodeList.getLength()];
            imageurl = new TextView[nodeList.getLength()];

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);

                id[i] = new TextView(this);
                imageurl[i] = new TextView(this);

                Element fstElmnt = (Element) node;
                NodeList idList = fstElmnt.getElementsByTagName("item_id");
                Element idElement = (Element) idList.item(0);
                idList = idElement.getChildNodes();
                id[i].setText("id is = " + ((Node) idList.item(0)).getNodeValue());

                NodeList imageurlList = fstElmnt.getElementsByTagName("item_image");
                Element imageurlElement = (Element) imageurlList.item(0);
                imageurlList = imageurlElement.getChildNodes();
                imageurl[i].setText("imageurl is = " + ((Node) imageurlList.item(0)).getNodeValue());

                layout.addView(id[i]);
                layout.addView(imageurl[i]);
            }
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        /** Set the layout view to display */
        setContentView(layout); 
    }
}

这篇关于在列表视图android中加载本地XML数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆