源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android编程使用sax解析xml数据的方法详解

  • 时间:2022-10-16 14:54 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android编程使用sax解析xml数据的方法详解
本文实例讲述了Android编程使用sax解析xml数据的方法。分享给大家供大家参考,具体如下: 随着技术的发展,现在的web已经和以前不同了。web已经逐渐像移动的方向倾斜,作为程序员的确应该拓展一下自己的知识层面。学习各方面的知识,今天就接着前几天的弄一下Android的xml解析,这次就使用sax的方式解析xml.下面就一步一步的来做吧。 [b]1. 编写一个简单的xml[/b]
<?xml version="1.0" encoding="UTF-8"?>
<persons>
 <person id="01">
   <name>will</name>
   <age>21</age>
 </person>
 <person id="02">
   <name>will2</name>
   <age>22</age>
 </person>
</persons>

[b]2. 编写pojo类[/b]
package org.lxh.vo;
public class Person {
  private String id;
  private String name;
  private int age;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String toString() {
    return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
}

[b]3.  写一个解析xml的类[/b]
package org.lxh.impl;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.lxh.vo.Person;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class Parse {
  public List<Person> findAll(InputStream in) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance(); //创建解析工厂
    SAXParser parser = factory.newSAXParser();
    ParsePerson chuli = new ParsePerson();
    parser.parse(in, chuli);
    in.close(); //关闭输入流
    return chuli.getData();
  }
  //开始解析xml
  public class ParsePerson extends DefaultHandler {
    List<Person> all = null;
    Person person = null;
    String flag = null;
    public List<Person> getData() {
      return all;
    }
    public void startDocument() throws SAXException {
      all = new ArrayList<Person>(); //实例化集合
    }
    public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
      if ("person".equals(localName)) {
        person = new Person();
        person.setId(attributes.getValue(0)); //取得id的内容
      }
      flag = localName; //记录上一个element
    }
    public void characters(char[] ch, int start, int length)
        throws SAXException {
      if (flag != null) { //这样做取得的值就不会重复
        String data = new String(ch, start, length);
        if ("name".equals(flag)) {
          person.setName(data);
        }
        else if ("age".equals(flag)) {
          person.setAge(Integer.parseInt(data));
        }
      }
    }
    public void endElement(String uri, String localName, String qName)
        throws SAXException {
      if ("person".equals(localName)) {
        all.add(person);
        person = null;
      }
      flag = null;
    }
  }
}

[b]4. 进行单元测试[/b]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="org.lxh.activity"
   android:versionCode="1"
   android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <uses-library android:name="android.test.runner"/>
    <activity android:name=".SaxParseXmlActivity"
         android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
  <instrumentation android:name="android.test.InstrumentationTestRunner"
  android:targetPackage="org.lxh.activity" android:label="TestforMyApp"/>
  <uses-sdk android:minSdkVersion="8" />
</manifest>

package org.lxh.activity;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.lxh.impl.Parse;
import org.lxh.vo.Person;
import android.test.AndroidTestCase;
import android.util.Log;
public class Test extends AndroidTestCase{
  public static final String tag="Test";
 public void testShuchu() throws Throwable{
   //Log.i(tag, "123");
   Parse p=new Parse();
   InputStream in=getClass().getClassLoader().getResourceAsStream("persons.xml");
    List<Person> all=p.findAll(in);
     Log.i(tag, String.valueOf(all.size()));
    Iterator<Person> it=all.iterator();
    while(it.hasNext()){
      Person person=it.next();
      Log.i(tag, person.toString());
    }
 }
}

最后来看一下运行效果图,这里最好弄个filter,控制台就没那么乱了。 [img]http://files.jb51.net/file_images/article/201707/2017717123031720.jpg?2017617123129[/img] 点击那个绿色的加号就OK了 [img]http://files.jb51.net/file_images/article/201707/2017717123134267.png?2017617123242[/img] [b]PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:[/b] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]在线格式化XML/在线压缩XML: [/b][url=http://tools.jb51.net/code/xmlformat]http://tools.jb51.net/code/xmlformat[/url] [b]XML[/b][b]在线压缩/格式化工具: [/b][url=http://tools.jb51.net/code/xml_format_compress]http://tools.jb51.net/code/xml_format_compress[/url] [b]XML[/b][b]代码在线格式化美化工具: [/b][url=http://tools.jb51.net/code/xmlcodeformat]http://tools.jb51.net/code/xmlcodeformat[/url] 更多关于Android相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/837.htm]Android操作XML数据技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/367.htm]Android编程之activity操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/423.htm]Android资源操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/325.htm]Android文件操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/410.htm]Android开发入门与进阶教程[/url]》、《[url=http://www.1sucai.cn/Special/375.htm]Android视图View技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/124.htm]Android控件用法总结[/url]》 希望本文所述对大家Android程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部