android dom修改xml文件,第62章、XML文件-DOM操作(从零开始学Android)

DOM解析原理是把xml文件的各种部分都看成是节点,所有的节点因为层级关系最后形成了一颗节点树。而DOM的解析方式便是在内存中生存这棵树,并允许用户进行相关的操作。

一、设计界面

1、布局文件

打开activity_main.xml文件。

输入以下代码:

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:id="@+id/save"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="保存XML数据(DOM)" />

android:id="@+id/read"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="读取XML数据(DOM)" />

二、程序文件

打开“src/com.genwoxue.filedom/MainActivity.java”文件。

然后输入以下代码:

package com.genwoxue.filedom;

import java.io.File;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.TransformerException;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import android.os.Bundle;

import android.os.Environment;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

import android.app.Activity;

public class MainActivity extends Activity {

private Button btnSave=null;

private Button btnRead=null;

private File file=null;

private static final String FILENAME="book.xml";

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

btnSave=(Button)super.findViewById(R.id.save);

btnRead=(Button)super.findViewById(R.id.read);

btnSave.setOnClickListener(new OnClickListener(){

public void onClick(View v)

{

DocumentBuilder builder=null;

Document doc=null;

Transformer trans=null;

//判断外部存储卡是否存在

if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();

return;

}

//初始化File

String path=Environment.getExternalStorageDirectory().toString()

+File.separator

+"genwoxue"

+File.separator

+FILENAME;

file=new File(path);

//如果当前文件的父文件夹不存在,则创建genwoxue文件夹

if(!file.getParentFile().exists())

file.getParentFile().mkdirs();

//实例化DocumentBuilderFactory

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

//获取DocumentBuilder对象

try {

builder=factory.newDocumentBuilder();

} catch (ParserConfigurationException e) {

e.printStackTrace();

}

//获取Document对象

doc=builder.newDocument();

//建立节点

Element books=doc.createElement("books");

Element book=doc.createElement("book");

Element bookname=doc.createElement("bookname");

Element author=doc.createElement("author");

Element publisher=doc.createElement("publisher");

//添加内容

bookname.appendChild(doc.createTextNode("跟我学Android"));

author.appendChild(doc.createTextNode("蒋老夫子"));

publisher.appendChild(doc.createTextNode("人民邮电出版社"));

//设置节点关系

book.appendChild(bookname);

book.appendChild(author);

book.appendChild(publisher);

books.appendChild(book);

doc.appendChild(books);

//输出到文件

TransformerFactory transfactory=TransformerFactory.newInstance();

try {

trans=transfactory.newTransformer();

} catch (TransformerConfigurationException e) {

e.printStackTrace();

}

trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8");

DOMSource source=new DOMSource(doc);

StreamResult result=new StreamResult(file);

try {

trans.transform(source, result);

} catch (TransformerException e) {

e.printStackTrace();

}

}

});

btnRead.setOnClickListener(new OnClickListener(){

public void onClick(View v)

{

DocumentBuilder builder=null;

Document doc=null;

StringBuffer info=null;

//判断外部存储卡是否存在

if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

Toast.makeText(getApplicationContext(), "读取失败,SD存储卡不存在!", Toast.LENGTH_LONG).show();

return;

}

//初始化File

String path=Environment.getExternalStorageDirectory().toString()

+File.separator

+"genwoxue"

+File.separator

+FILENAME;

file=new File(path);

if(!file.exists()){

Toast.makeText(getApplicationContext(), "文件不存在!", Toast.LENGTH_LONG).show();

return;

}

//实例化DocumentBuilderFactory

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();

//获取DocumentBuilder对象

try {

builder=factory.newDocumentBuilder();

} catch (ParserConfigurationException e) {

e.printStackTrace();

}

//获取Document对象

try {

doc=builder.parse(file);

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

//查找book节点

NodeList nodelist=doc.getElementsByTagName("book");

//获取节点文本内容

info=new StringBuffer();

for(int i=0;i

Element element=(Element)nodelist.item(i);

info.append(info+element.getElementsByTagName("bookname").item(0).getFirstChild().getNodeValue()).append("☆☆☆");

info.append(element.getElementsByTagName("author").item(0).getFirstChild().getNodeValue()).append("☆☆☆");

info.append(element.getElementsByTagName("publisher").item(0).getFirstChild().getNodeValue()).append("☆☆☆");

}

Toast.makeText(getApplicationContext(), info.toString(), Toast.LENGTH_LONG).show();

}

});

}

}

三、配置文件

打开“AndroidManifest.xml”文件。

然后输入以下代码:

package="com.genwoxue.filedom"

android:versionCode="1"

android:versionName="1.0" >

android:minSdkVersion="8"

android:targetSdkVersion="15" />

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

android:name="com.genwoxue.filedom.MainActivity"

android:label="@string/app_name" >

注意:由于要进行读写外部存储卡操作,故而需要在AndroidManifest.xml文件中添加两项权限:

四、运行结果

f39e9b38779dccfba2cc4476ca0c6431.png 

46ea5bf721cd89543ee6a73467b58621.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值