1. 程式人生 > >android最最基礎簡單的儲存xml程式碼

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>