Android_Xml 文件(数据) 生成 与 解析

一 xml文件生产
使用 XmlSerializer 类,编写数据

File file = new File(getFilesDir(), "user.xml");
String name = etUser.getText().toString().trim();
String psw = etPsw.getText().toString().trim();
try {
    OutputStream os = new FileOutputStream(file); 
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(os, "UTF-8");   //设置输出流

    serializer.startDocument("UTF-8", true);

    serializer.startTag(null, "user");

    serializer.startTag(null, "name");
    serializer.text(name);
    serializer.endTag(null, "name");

    serializer.startTag(null, "psw");
    serializer.text(psw);
    serializer.endTag(null, "psw");

    serializer.endTag(null, "user");

    serializer.endDocument();

    os.close();

    Toast.makeText(getApplicationContext(), "success", 0).show();

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

二 解析xml 文件(数据)
使用 XmlPullParser 类解析

try {
    File file = new File(getFilesDir(), "user.xml");
    XmlPullParser pullParser = Xml.newPullParser();
    InputStream is = new FileInputStream(file);
    pullParser.setInput(is, "UTF-8");

    int evenType = pullParser.getEventType();
    while(evenType != pullParser.END_DOCUMENT) {

        if(evenType == pullParser.START_TAG){
            if(pullParser.getName().equals("name")) {
            /*
             * <user type="">
             * 如果在 TAG 中含有属性  
             * String type = pullParser.getAttributeValue(index); //获取属性值
             * index 代表 第几个属性
             */

                tvUser.setText(pullParser.nextText());
            } else if(pullParser.getName().equals("psw")) {
                tvPsw.setText(pullParser.nextText());
            }
        }
        evenType = pullParser.next();
    }
    is.close();
    Toast.makeText(getApplicationContext(), "PullParser success", 0).show();
} catch (Exception e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值