XML文件写入和读取

前端之家收集整理的这篇文章主要介绍了XML文件写入和读取前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

还是用登录页面作为例子



public void login(View v){
if(cb.isChecked()){//选中复选框
Toast.makeText(this,"读取文件",Toast.LENGTH_LONG);
readxml(this);
}else{
Toast.makeText(this,"写入文件",Toast.LENGTH_LONG);
writexmls(this);


}
}



写入数据成为xml

public void writexmls(Context ct){
XmlSerializer xmls=Xml.newSerializer();
File ff=new File(ct.getFilesDir().toString(),"serial.xml");
FileOutputStream os= null;
try {
os = new FileOutputStream(ff);
xmls.setOutput(os,"utf-8");
xmls.startDocument("utf-8",true);
xmls.startTag(null,"groupnodes");
xmls.startTag(null,"name");
xmls.attribute(null,"id","1");
xmls.text(et_username.getText().toString());
xmls.endTag(null,"name");


xmls.startTag(null,"pwd");
xmls.text(et_password.getText().toString());
xmls.endTag(null,"pwd");
xmls.endTag(null,"groupnodes");
xmls.endDocument();
} catch (Exception e) {
e.printStackTrace();
}
}

文件路径



XML文件用XMLSerializer 写入数据,

用XMLPullParser读取xml数据


文件serial.xml文件内容

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>

<groupnodes><name id="1"></name><pwd></pwd></groupnodes>


从xml读取文件

public void readxml(Context ct){ XmlPullParser xpp=Xml.newPullParser(); File ff=new File(ct.getFilesDir().toString(),"serial.xml"); try{ InputStream ips=new FileInputStream(ff); xpp.setInput(ips,"utf-8"); int et=xpp.getEventType(); while(et!=XmlPullParser.END_DOCUMENT){ String name=xpp.getName(); String tt=xpp.getText(); if(name!=null){ if(name.equals("name")){ et_username.setText(xpp.nextText()); }else if(name.equals("pwd")){ et_password.setText(xpp.nextText()); } } et=xpp.next(); } }catch (Exception e) { e.printStackTrace(); } }

原文链接:https://www.f2er.com/xml/295389.html

猜你在找的XML相关文章