zoukankan      html  css  js  c++  java
  • android SAX 解析 xml文档【转】

    res/layout/main014.xm

    View Code
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation
    ="vertical" android:layout_width="fill_parent"
    android:layout_height
    ="fill_parent">
    <TextView android:text="用户Id" android:layout_width="wrap_content"
    android:layout_height
    ="wrap_content"></TextView>
    <EditText android:text="" android:layout_width="fill_parent"
    android:layout_height
    ="wrap_content" android:id="@+id/userid"
    android:singleLine
    ="true"></EditText>
    <TextView android:text="用户名" android:layout_width="wrap_content"
    android:layout_height
    ="wrap_content"></TextView>
    <EditText android:text="" android:layout_width="fill_parent"
    android:layout_height
    ="wrap_content" android:id="@+id/username"
    android:singleLine
    ="true"></EditText>
    <TextView android:text="用户密码" android:layout_width="wrap_content"
    android:layout_height
    ="wrap_content"></TextView>
    <EditText android:text="" android:layout_width="fill_parent"
    android:layout_height
    ="wrap_content" android:id="@+id/password"
    android:singleLine
    ="true"></EditText>
    <TextView android:text="用户信息" android:layout_width="wrap_content"
    android:layout_height
    ="wrap_content"></TextView>
    <EditText android:text="" android:layout_width="fill_parent"
    android:layout_height
    ="wrap_content" android:id="@+id/info"
    android:singleLine
    ="true"></EditText>
    <Button android:text="To XML" android:id="@+id/toXml"
    android:layout_width
    ="fill_parent" android:layout_height="wrap_content"></Button>
    <Button android:text="Read XML" android:id="@+id/readXml"
    android:layout_width
    ="fill_parent" android:layout_height="wrap_content"></Button>


    </LinearLayout>

    res/layout/read.xml

    View Code
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width
    ="fill_parent" android:layout_height="wrap_content"
    android:orientation
    ="vertical">
    <LinearLayout android:layout_width="fill_parent"
    android:layout_height
    ="fill_parent">
    <TextView android:text="用户id:\n" android:layout_width="wrap_content"
    android:layout_height
    ="wrap_content"></TextView>
    <TextView android:text="" android:id="@+id/r_userid"
    android:layout_width
    ="wrap_content" android:layout_height="wrap_content"></TextView>
    </LinearLayout>

    <LinearLayout android:layout_width="fill_parent"
    android:layout_height
    ="fill_parent">
    <TextView android:text="用户名:\n" android:id="@+id/textView1"
    android:layout_width
    ="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="" android:id="@+id/r_username"
    android:layout_width
    ="wrap_content" android:layout_height="wrap_content"></TextView>
    </LinearLayout>

    <LinearLayout android:layout_width="fill_parent"
    android:layout_height
    ="fill_parent">
    <TextView android:text="用户密码:\n" android:id="@+id/textView1"
    android:layout_width
    ="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="" android:id="@+id/r_password"
    android:layout_width
    ="wrap_content" android:layout_height="wrap_content"></TextView>
    </LinearLayout>

    <LinearLayout android:layout_width="fill_parent"
    android:layout_height
    ="fill_parent">
    <TextView android:text="用户信息:\n" android:id="@+id/textView1"
    android:layout_width
    ="wrap_content" android:layout_height="wrap_content"></TextView>
    <TextView android:text="" android:id="@+id/r_info"
    android:layout_width
    ="wrap_content" android:layout_height="wrap_content"></TextView>
    </LinearLayout>
    </LinearLayout>

    src/B.Unit/User.java

    View Code
    package B.Unit;

    public class User {
    private int userId;
    private String userName;
    private String password;
    private String info;

    public int getUserId() {
    return userId;
    }

    public void setUserId(int userId) {
    this.userId = userId;
    }

    public String getUserName() {
    return userName;
    }

    public void setUserName(String userName) {
    this.userName = userName;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    public String getInfo() {
    return info;
    }

    public void setInfo(String info) {
    this.info = info;
    }

    }

    src/B.Unit/SaxDoc.java

    package B.Unit;

    import java.util.ArrayList;
    import java.util.List;

    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;

    /**
    * 实现丢xml文件解析,返回一个list对象
    *
    * */

    public class SaxDoc extends DefaultHandler {
    private List
    <User> list = null;
    private User user = null;
    private String tagname;

    /**
    * 开始解析xml文档
    * */
    @Override
    public void startDocument() throws SAXException {
    System.out.println("startDocument");
    list = new ArrayList
    <User>();
    super.startDocument();
    }

    StringBuffer sb = new StringBuffer();
    /**
    * 开始处理节点,获得节点的属性
    * */
    @Override
    public void startElement(String uri, String localName, String qName,
    Attributes attributes) throws SAXException {
    sb.delete(0, sb.length());
    if (localName.equals("user")) {
    user = new User();
    user.setUserId(Integer.parseInt(attributes.getValue("id")));
    }
    this.tagname = localName;
    super.startElement(uri, localName, qName, attributes);
    }

    /**
    * 获取节点内容
    * */
    @Override
    public void characters(char[] ch, int start, int length)
    throws SAXException {

    if (this.tagname != "") {
    if (this.tagname.equals("name")) {
    sb.append(ch, start, length);
    user.setUserName(sb.toString());
    } else if (this.tagname.equals("pwd")) {
    sb.append(ch, start, length);
    user.setPassword(sb.toString());
    } else if (this.tagname.equals("info")) {
    sb.append(ch, start, length);
    user.setInfo(sb.toString());
    }
    }
    super.characters(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
    throws SAXException {
    // 一个元素结束后往list里加入一个user对象
    if (localName.equals("user")) {
    list.add(user);
    }
    super.endElement(uri, localName, qName);
    }

    @Override
    public void endDocument() throws SAXException {
    super.endDocument();
    }

    // 返回user list对象
    public List
    <User> getUserList() {
    return list;
    }
    }

    src/B.Unit/SaxWriteXml.java

    package B.Unit;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.StringWriter;
    import java.util.List;

    import org.xmlpull.v1.XmlSerializer;

    import android.os.Environment;
    import android.util.Xml;

    public class SaxWriteXml {

    public String writeUserInfoToString(List
    <User> users) {

    // 实现xml信息序列化的一个对象
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
    // xml数据经过序列化后保存到String中,然后将字符串通过OutputStream保存为xml文件
    serializer.setOutput(writer);
    // 文档开始
    serializer.startDocument("utf-8", true);
    // 开始一个节点
    serializer.startTag("", "users");
    // 开始一个子节点
    for (User user : users) {
    serializer.startTag("", "user");
    serializer
    .attribute("", "id", String.valueOf(user.getUserId()));

    serializer.startTag("", "name");
    serializer.text(user.getUserName());
    serializer.endTag("", "name");

    serializer.startTag("", "pwd");
    serializer.text(user.getPassword());
    serializer.endTag("", "pwd");

    serializer.startTag("", "info");
    serializer.text(String.valueOf(user.getInfo()));
    serializer.endTag("", "info");

    serializer.endTag("", "user");
    }
    serializer.endTag("", "users");

    // 关闭文档
    serializer.endDocument();

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

    return writer.toString();
    }

    public boolean writeToXml( String str,String filePat) {
    System.out.println("run==>writeToXml");
    OutputStream out = null;
    try {
    String dirPath = Environment.getExternalStorageDirectory()
    .toString() + "/xml";
    File dir = new File(dirPath);
    if (!dir.exists())
    dir.mkdir();
    File f = new File(dirPath +"/"+ filePat);
    System.out.println(dirPath +"/"+ filePat);
    out = new FileOutputStream(f);

    } catch (Exception e) {
    System.out.println("Error"+e.getMessage());
    return false;
    }
    OutputStreamWriter outw = new OutputStreamWriter(out);
    try {
    outw.write(str);
    outw.close();
    out.close();
    } catch (Exception e) {
    return false;
    }
    return true;
    }
    }

    src/B.Unit/Activity014.java

    package B.P1;

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;

    import org.xml.sax.SAXException;

    import B.Unit.SaxDoc;
    import B.Unit.SaxWriteXml;
    import B.Unit.User;
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.os.Environment;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Activity014 extends Activity {

    private EditText userid, username, password, info;
    private Button toXml, readXml;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main014);

    userid
    = (EditText) findViewById(R.id.userid);
    username
    = (EditText) findViewById(R.id.username);
    password
    = (EditText) findViewById(R.id.password);
    info
    = (EditText) findViewById(R.id.info);

    toXml
    = (Button) findViewById(R.id.toXml);
    toXml.setOnClickListener(toXmlClick);

    readXml
    = (Button) findViewById(R.id.readXml);
    readXml.setOnClickListener(readXmlClick);

    }

    OnClickListener toXmlClick
    = new OnClickListener() {

    @Override
    public void onClick(View v) {
    System.out.println(
    "toXmlButton onclick");
    // 用户Id必须填入一个数字否则会出现转换数字异常
    String id = userid.getText().toString();
    String user
    = username.getText().toString();
    String pwd
    = password.getText().toString();
    String _info
    = info.getText().toString();

    User u
    = new User();

    u.setUserId(
    new Integer(id));
    u.setUserName(user);
    u.setPassword(pwd);
    u.setInfo(_info);
    // 如果有多个User对象,可以继续添加
    List<User> list = new ArrayList<User>();
    list.add(u);

    SaxWriteXml sax
    = new SaxWriteXml();
    String strXml
    = sax.writeUserInfoToString(list);
    System.out.println(strXml);
    sax.writeToXml(strXml,
    "user.xml");

    Toast.makeText(getApplicationContext(),
    "write to xml file successful ", Toast.LENGTH_SHORT).show();
    }
    };

    OnClickListener readXmlClick
    = new OnClickListener() {

    @Override
    public void onClick(View v) {
    System.out.println(
    "readXmlButton onclick");

    SaxDoc sax
    = new SaxDoc();

    SAXParser sp
    = null;
    try {
    sp
    = SAXParserFactory.newInstance().newSAXParser();
    }
    catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

    }
    catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

    }
    catch (FactoryConfigurationError e) {
    // TODO Auto-generated catch block

    e.printStackTrace();

    }
    // 解析user.xml文件
    File f = new File(Environment.getExternalStorageDirectory()
    .toString()
    + "/xml/user.xml");
    System.out.println(Environment.getExternalStorageDirectory()
    .toString()
    + "/xml/user.xml");

    if (!f.exists()) {
    Toast.makeText(getApplicationContext(),
    "not exist user.xml ",
    Toast.LENGTH_SHORT).show();
    return;
    }
    try {
    sp.parse(f, sax);
    System.out.println(
    "sp.parse(f, sax);");
    }
    catch (SAXException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

    }
    catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    // 解析user.xml后,获取返回list的user数据
    List<User> list = sax.getUserList();
    // 目前只有一个User对象
    User user = list.get(0);
    int r_userid = user.getUserId();
    String r_username
    = user.getUserName();
    String r_password
    = user.getPassword();
    String r_info
    = user.getInfo();

    System.out.println(
    "r_userid" + r_userid);
    System.out.println(
    "r_username" + r_username);
    System.out.println(
    "r_password" + r_password);
    System.out.println(
    "r_info" + r_info);

    Intent intent
    = new Intent(Activity014.this, Activity014Read.class);
    Bundle map
    = new Bundle();
    map.putSerializable(
    "r_userid", r_userid);
    map.putSerializable(
    "r_username", r_username);
    map.putSerializable(
    "r_password", r_password);
    map.putSerializable(
    "r_info", r_info);
    intent.putExtra(
    "user", map);
    startActivity(intent);

    }
    };

    }

    src/B.Unit/Activity014Read.java

    View Code
    package B.P1;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;

    public class Activity014Read extends Activity {

    private TextView userid, username, password, info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.read);

    int _userid = this.getIntent().getBundleExtra("user")
    .getInt(
    "r_userid");

    String _username
    = this.getIntent().getBundleExtra("user")
    .getString(
    "r_username");

    String _password
    = this.getIntent().getBundleExtra("user")
    .getString(
    "r_password");

    String _info
    = this.getIntent().getBundleExtra("user")
    .getString(
    "r_info");

    userid
    = (TextView) findViewById(R.id.r_userid);
    username
    = (TextView) findViewById(R.id.r_username);
    password
    = (TextView) findViewById(R.id.r_password);
    info
    = (TextView) findViewById(R.id.r_info);

    System.out.println(
    "_userid" + _userid);
    System.out.println(
    "_username" + _username);
    System.out.println(
    "_password" + _password);
    System.out.println(
    "_info" + _info);

    userid.setText(String.valueOf(_userid));
    username.setText(_username);
    password.setText(_password);
    info.setText(_info);
    }
    }
  • 相关阅读:
    LGPrep的一点小问题
    百度地图API的事件处理:覆盖物阻止冒泡
    HTML5截取视频第一帧作为预览图片
    20165105 第二周学习总结
    20165105课下作业
    20165105第一周学习查缺补漏
    第四周课下作业20165105
    20165105 201620172 《Java程序设计》第1周学习总结
    我期望的师生关系
    .NET使用NPOI组件将数据导出Excel
  • 原文地址:https://www.cnblogs.com/xiaobuild/p/2153315.html
Copyright © 2011-2022 走看看