android 基础一 <XML读写>

方式一:字符串拼接

StringBuilder sb=new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<root>");
sb.append("<book>android 基础<book>");
sb.append("</root>");
File path = new File(Environment.getExternalStorageDirectory().getPath(), "config.xml");
FileOutputStream fos= new FileOutputStream(path);
fos.write(sb.toString().getBytes());
fos.close();

方式二: XmlSerializer

  private void XmlSerializerTest() throws IOException {
       // 1.获取XmlSerializer 类的实例,通过xml获取
        XmlSerializer serializer= Xml.newSerializer();
        File file=new File(Environment.getExternalStorageDirectory(),"config.xml");
        FileOutputStream fos=new FileOutputStream(file);
        //读写流的编码格式
        serializer.setOutput(fos,"utf-8");
       // 2.写xml开头,xml 头部的编码格式utf-8
        serializer.startDocument("utf-8",true);
        //3.写节点,命名空间xmlns ,如AndroidManifest里面定义的xmlns
        serializer.startTag(null,"root");//root开始节点

        serializer.startTag(null,"book");//book开始节点
        serializer.text("android基础");
        serializer.endTag(null,"book");//book结束节点

        serializer.endTag(null,"root");//root结束节点
        // xml结束
        serializer.endDocument();
    }

猜你喜欢

转载自www.cnblogs.com/jtzp007/p/10960183.html