解析XML

Pull解析

1、获取XmlPullParserFactory实例

  XmlPullParserFactory factory = XmlPullParserFactory.newInstanc();

2、借助XmlPullparserFactory实例获取XmlPullParser对象

  XmlPullParser xmlPullParser = factory.newPullParser();

3、调用setInput()解析数据

  xmlPullParserl.setInput(new StringReader(xmlData));

4、调用getEvent()得到当前解析事件

  int eventType = xmlPullParser.getEventType();

5、利用while循环解析

  while(eventType != XmlPullParser.END_DOCUMENT){

    String nodeName = xmlPullParser.getName();

    switch(eventType){

      case XmlPullParser.START_TAG:{

        if("id".equals(nodeName)){

          id = xmlPullParser.nextText();

        }else if("name".equals(nodeName)){

          name = xmlPullParser.nextText();

        }else if("version".equals(nodeName)){

          version = xmlPullParser.nextText();

        }

        break;

      }

    //完成解析某个节点

    case XmlPullParser.END_TAG:{

      if("app".equals(nodeName)){

        Log.d("MainActivity","id is"+id);

        Log.d("MainActivity","name is"+name);

        Log.d("MainActivity","version is"+version);

      }

      break;

    default:

      break;

  }

  eventType = xmlPullParser.next();

 }

......

 

SAX解析

1、创建一个类继承自DefaultHandler,并重写5个方法(startDocument()、startElement()、characters()、endElement()、endDocument())

2、创建SAXParserFactory实例

  SAXParserFactory factory = SAXParserFactory.newInstance();

3、通过factory创建XMLReader对象

  XMLReader xmlReader = factory.newSAXParser().getXMLReader();

4、创建ContentHandler对象

  ContentHandler handler = new ContentHandler();

5、将ContentHandler的实例设置到XMLReader中

  xmlReader.setContentHandler(handler);

6、开始解析

  xmlParser.parse(new InputSource(new StringReader(xmlData)));

          

  

posted @ 2017-02-20 22:09  yl007  阅读(117)  评论(0编辑  收藏  举报