Android中写入读取XML
获取XML文件的基本思路是,通过getResources().getXml()获的XML原始文件,得到XmlResourceParser对象,通过该对象来判断是文档的开头还是结尾,是某个标签的开始还是结尾,并通过一些获取属性的方法来遍历XML文件,从而访问XML文件的内容,下面是一个访问XML文件内容的例子,并将内容更显示在一个TextView上
数据写入xml:
ReadXMLTest.java
- //xml数据生成
- private String WriteToString() {
- XmlSerializer serializer = Xml.newSerializer();
- StringWriter writer = new StringWriter();
- try {
- serializer.setOutput(writer);
- serializer.startDocument("utf-8", true);
- serializer.startTag("", "users");
- serializer.startTag("", "userName");
- serializer.text(txtUser.getText().toString());
- serializer.endTag("", "userName");
- serializer.startTag("", "userEmail");
- serializer.text(txtEmail.getText().toString());
- serializer.endTag("", "userEmail");
- serializer.startTag("", "passWord");
- serializer.text(txtPass.getText().toString());
- serializer.endTag("", "passWord");
- serializer.endTag("", "users");
- serializer.endDocument();
- } catch (IllegalArgumentException e) {
- // TODO: handle exception
- e.printStackTrace();
- } catch (IllegalStateException e) {
- // TODO: handle exception
- e.printStackTrace();
- } catch (IOException e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- return writer.toString();
- }
- //将字符串保存为apk的私有文件
- private boolean writeToXml(String str) {
- try {
- OutputStream out = openFileOutput("users.xml",MODE_PRIVATE);
- OutputStreamWriter outWriter = new OutputStreamWriter(out);
- try {
- outWriter.write(str);
- outWriter.close();
- out.close();
- return true;
- } catch (IOException e) {
- // TODO: handle exception
- return false;
- }
- } catch (Exception e) {
- // TODO: handle exception
- return false;
- }
- }
调用时:
if(writeToXml(WriteToString()))
{
//成功
}
数据读取 xml:
- //tag ,存入的节点名
- private String ReadXmlUser(String tag)
- {
- String re="";
- DocumentBuilderFactory documentBuilderFactory;
- DocumentBuilder documentBuilder;
- Document document;
- try {
- documentBuilderFactory=DocumentBuilderFactory.newInstance();
- documentBuilder=documentBuilderFactory.newDocumentBuilder();
- //xml文件放到assets目录下
- document=documentBuilder.parse(this.openFileInput("users.xml"));
- org.w3c.dom.Element root= document.getDocumentElement();
- NodeList nodeList=root.getElementsByTagName(tag);
- Node nd=nodeList.item(0);
- re= nd.getFirstChild().getNodeValue();
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }finally{
- document=null;
- documentBuilder=null;
- documentBuilderFactory=null;
- }
- return re;
- }
出处:http://cnblogs.com/daishuguang