使用Sax Parser解析XML数据

时间:2014-01-16 05:42:57

标签: android xml

我在android工作,需要帮​​助解析下面的XML数据并在listview上显示它。我正在使用Sax Parser来解析数据

<NotifyList>
<Notify><Name>Raj</Name><Age>12</Age><Status>1</Status></Notify>

<Notify><Name>G</Name><Age>11</Age><Status>2</Status></Notify>

<Notify><Name>D</Name><Age>21</Age><Status>1</Status><Mobile>23232324</Mobile></Notify>

<Notify><Name>erwer</Name><Age>3</Age><Status>2</Status><Mobile>235534</Mobile></Notify>

<NotifyList>

在上面的xml数据中,您可以找到Mobile标记缺少第1行和第2行。如果标签不存在,我必须检查标签是否存在我需要在列表视图中将其附加到空值,如下所示。

姓名1年龄&gt;

Name2年龄&gt;

姓名3年龄Ph没有&gt;

Name4 Age Ph No&gt;

Thanxs, Goutham

1 个答案:

答案 0 :(得分:0)

 ArrayList<String> parsedtxt =new ArrayList<String>();


           try {   
                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();

                DefaultHandler handler = new DefaultHandler() {
                boolean partxt = false;


                @Override
                public void startElement(String uri, String localName,
                String qName, Attributes attributes)
                throws SAXException {               

                if (qName.equalsIgnoreCase("Notify")) {
                    partxt = true;
                }


                }



                @Override
                public void endElement(String uri, String localName,
                String qName) throws SAXException {
                // TODO Auto-generated method stub          
                }

                @Override
                public void characters(char[] ch, int start, int length)
                throws SAXException {
                // TODO Auto-generated method stub

                if (partxt) {
                System.out.println("Product : " + new String(ch, start, length).trim());
                parsedtxt.add(new String(ch, start, length).trim());


                }


                }
                     };
                     asset = this.getAssets();
                     in = asset.open(xmlnam+"det.xml");

                     saxParser.parse(in, handler);

                     } catch (Exception e) {

                     }
相关问题