第四十六篇--解析和保存xml文件
新建assets资源文件夹,右键app --> new --> Folder --> Assets Folder,将info.xml放入此文件夹下面。
info.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <info> <student id="10011"> <name>lisi</name> <age>19</age> </student> </info>
解析:
MainActivity.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.aimee.getfileinfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.util.Xml; import android.view.View; import org.xmlpull.v1.XmlPullParser; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View view) { try { //1.找到此资产文件并打开 InputStream is = this.getAssets().open("info.xml");//ctrl+shift+方向键可以上下移动 //2.得到xml文件解析器 XmlPullParser parser = Xml.newPullParser(); //3.设置输入流和编码 parser.setInput(is,"utf-8"); //4.解析xml文件,获取当前的事件类型 int type = parser.getEventType(); while (type != XmlPullParser.END_DOCUMENT){ Log.i(TAG,parser.getEventType() + "----" + parser.getName() + "----" + parser.getText()); type = parser.next(); } is.close(); } catch (Exception e) { e.printStackTrace(); } } }
保存:
MainActivity.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.aimee.getfileinfo; import android.Manifest; import android.os.Bundle; import android.os.Environment; import android.text.TextUtils; import android.util.Xml; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.xmlpull.v1.XmlSerializer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends com.example.aimee.getfileinfo.BaseActivity { private EditText mEtAge; private EditText mEtName; private EditText mEtId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1.找到所有需要用到的文件 mEtName = findViewById(R.id.et_name); mEtAge = (EditText) findViewById(R.id.et_age); mEtId = (EditText) findViewById(R.id.et_id); //2.将控件内容写到xml文件中 } /** * 将控件内容写到xml文件中 * @param view */ public void save(View view) { //3.根据控件读取用户输入的文本放入到字符串变量中 final String name = mEtName.getText().toString().trim(); final String age = mEtAge.getText().toString().trim(); final String id = mEtId.getText().toString().trim(); //4.判断是否有空的内容 if (TextUtils.isEmpty(name) || TextUtils.isEmpty(age)){ Toast.makeText(this,"信息不能为空",Toast.LENGTH_SHORT).show(); return; }else { //5.将字符串写入到xml文件中 performCodeWithPermission("保存学生信息到sd卡", new PermissionCallback() { @Override public void hasPermission() { //1.创建一个xml文件的序列号器 XmlSerializer serializer = Xml.newSerializer(); //2.设置文件的输出和编码方式 FileOutputStream fos = null; try { fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "info.xml")); serializer.setOutput(fos,"utf-8"); //3.写入xml文件的头 serializer.startDocument("utf-8",true); //4.写info节点 serializer.startTag(null,"info"); //5.写student节点 serializer.startTag(null,"student"); //6.写属性 serializer.attribute(null,"id",id); //7.写name serializer.startTag(null,"name"); serializer.text(name); serializer.endTag(null,"name"); //8.写age serializer.startTag(null,"age"); serializer.text(age); serializer.endTag(null,"age"); serializer.endTag(null,"student"); serializer.endTag(null,"info"); serializer.endDocument();; } catch (Exception e) { e.printStackTrace(); }finally { try { if (fos !=null) fos.close(); Toast.makeText(MainActivity.this,"成功保存文件",Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void noPermission() { Toast.makeText(MainActivity.this,"没有运行时权限",Toast.LENGTH_SHORT).show(); } }, Manifest.permission.WRITE_EXTERNAL_STORAGE); } } }
activity_main.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/et_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="60dp" android:layout_marginEnd="8dp" android:ems="10" android:hint="请输入学生的姓名" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/et_age" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="60dp" android:layout_marginEnd="8dp" android:ems="10" android:hint="请输入学生的年龄" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_name" /> <EditText android:id="@+id/et_id" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginTop="60dp" android:layout_marginEnd="8dp" android:ems="10" android:hint="请输入学生的学号" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_age" /> <Button android:id="@+id/button" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="9dp" android:layout_marginTop="60dp" android:layout_marginEnd="8dp" android:text="保存" android:onClick="save" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_id" /> </android.support.constraint.ConstraintLayout>
注意:不要忘了在清单文件中添加权限。