android最最基础简单的保存xml代码

y偶遇非常基础,我想直接上代码:

MainActivity.java:

package com.lgqchinese.xmlcreate;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;

import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void myClick(View view) {

        try {
            XmlSerializer serializer = Xml.newSerializer();
            File file = new File("/data/data/com.lgqchinese.xmlcreate/text.xml");
            FileOutputStream fos = new FileOutputStream(file);
            serializer.setOutput(fos, "utf-8");
            serializer.startDocument("utf-8", true);
            serializer.startTag(null, "smss");
            serializer.startTag(null, "sms");
            serializer.startTag(null, "text");
            serializer.text("text内容1");
            serializer.endTag(null, "text");
            serializer.startTag(null, "text");
            serializer.text("text内容2");
            serializer.endTag(null, "text");
            serializer.startTag(null, "text");
            serializer.text("text内容3");
            serializer.endTag(null, "text");
            serializer.endTag(null, "sms");
            serializer.endTag(null, "smss");
            serializer.endDocument();
            fos.close();
            System.out.println("保存成功");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("未找到文件");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("输入流异常");
        }

    }
}

结果为:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<smss>
    <sms>
        <text>text内容1</text>
        <text>text内容2</text>
        <text>text内容3</text>
    </sms>
</smss>

 

posted @ 2018-10-26 18:39  龙谷情Sinoam  阅读(744)  评论(0编辑  收藏  举报
Smiley face