数据存储-XML文件(DOM/SAX/PULL解析)

前端之家收集整理的这篇文章主要介绍了数据存储-XML文件(DOM/SAX/PULL解析)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

之前研究xml解析的时候总结的笔记,下面代码有部分是省略的,只保留主要部分,希望能给初学者有点启发。

1、使用DOM输出XML

步骤:

(1)DocumentBuilderFactory ->DocumentBuilder -> Document

DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance() ;

DocumentBuilderbuilder =factory.newDocumentBuilder()

Documentdoc =builder.newDocument()

(2)创建节点标签

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

(3)创建内容节点

doc.createTextNode( " ")

(4)添加子节点

name .appendChild()


。。。

private class OnClickListenerImpl implementsOnClickListener{

@Override

publicvoid onClick(View v) {

if(!Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED)){// 不存在不操作

return; // 返回到程序的被调用

}

Filefile = new File(Environment.getExternalStorageDirectory()

+File.separator + "mldndata" + File.separator

+"member.xml");// 要输出文件的路径

if (!file.getParentFile().exists()) { // 父路径不存在

file.getParentFile().mkdirs();// 创建父文件

}

DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance() ;

DocumentBuilderbuilder = null ;

builder = factory.newDocumentBuilder();

Documentdoc = null ;

doc = builder.newDocument();// 创建一个新的文档

Elementaddresslist = doc.createElement("addresslist");

Elementlinkman = doc.createElement("linkman") ;

Elementname = doc.createElement("name") ;

Elementemail = doc.createElement("email") ;

name.appendChild(doc.createTextNode(MyDOMDemo.this.name.getText()

.toString()));//添加控件的内容进节点

email.appendChild(doc.createTextNode(MyDOMDemo.this.email.getText()

.toString()));

linkman.appendChild(name);

linkman.appendChild(email);

addresslist.appendChild(linkman);

doc.appendChild(addresslist);

TransformerFactory tf =TransformerFactory.newInstance() ;

Transformert = null ;

t= tf.newTransformer() ;

t.setOutputProperty(OutputKeys.ENCODING,"GBK") ;

DOMSource source = new DOMSource(doc);

StreamResultresult = new StreamResult(file) ;

t.transform(source,result) ;

}

}

}

2、通过DOM读取XML

步骤:

(1)DocumentBuilderFactory ->DocumentBuilder -> Document

DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance() ;

DocumentBuilderbuilder =factory.newDocumentBuilder()

(2)通过文件转化文档

Documentdoc =builder.parse(file)

(3)取得标签元素的节点列表

NodeList nl = doc.getElementsByTagName("linkman")

(4)取得节点元素对象Element

nl.item(x)

getNodeValue()取节点的值

public classMyDOMDemo extends Activity {

。。。。。。

privateclass OnClickListenerImpl implements OnClickListener {

@Override

publicvoid onClick(View v) {

。。。。。。

Documentdoc = null;

doc = builder.parse(file);// 通过文件转化文档

NodeListnl = doc.getElementsByTagName("linkman");

for(int x = 0; x < nl.getLength(); x++) {

Element e = (Element) nl.item(x); // 取得元素

MyDOMDemo.this.name.setText(e.getElementsByTagName("name")

.item(0).getFirstChild().getNodeValue());

MyDOMDemo.this.email.setText(e.getElementsByTagName("email")

.item(0).getFirstChild().getNodeValue());

}

}

}

}

3、SAX解析

步骤:

(1)SAXParserFactory ->SAXParser ->parse(file,sax) ->DefaultHandler

SAXParserFactory factory =SAXParserFactory.newInstance() ;

SAXParserparser= factory.newSAXParser() ;

MySAX sax = new MySAX() ;

parser.parse(file,sax) ;

List<LinkMan> all = sax.getAll() ;

(2)

(3)

//每一个LinkMan 类的对象

都表示一条LinkMan 节点的内容

public class LinkMan{

privateString name;

privateString email;

publicString getName() {

returnname;

}

publicvoid setName(String name) {

this.name= name;

}

publicString getEmail() {

returnemail;

}

publicvoid setEmail(String email) {

this.email= email;

}

}

MySAX

//解析器

public class MySAXextends DefaultHandler {

private List<LinkMan> all = null;// 保存多条数据

privateLinkMan man = null ;

private String elementName = null;// 保存节点的名称

@Override

publicvoid characters(char[] ch,int start,int length)

throwsSAXException {

if(this.elementName != null){// 已经取得了元素名称

Stringdata = new String(ch,start,length) ;

if("name".equals(this.elementName)){

this.man.setName(data);

}else if ("email".equals(this.elementName)) {

this.man.setEmail(data);

}

}

}

@Override

publicvoid endElement(String uri,String localName,String qName)

throwsSAXException {

if("linkman".equals(localName)){

this.all.add(this.man);

this.man = null;// 准备保存下次的数据

}

this.elementName = null;// 把元素名称清空

}

@Override

publicvoid startDocument() throws SAXException {

this.all = new ArrayList<LinkMan>();// 表示开始解析文档,所以要设置集合

}

@Override

publicvoid startElement(String uri,String qName,

Attributesattributes) throws SAXException {

if("linkman".equals(localName)){// 是一个linkman节点

this.man = new LinkMan();// 实例化LinkMan对象

}

this.elementName = localName;// 保存元素名称

}

publicList<LinkMan> getAll() {

returnall;

}

}

MyDOMDemo

public classMyDOMDemo extends Activity {

。。。。。。

privateclass OnClickListenerImpl implements OnClickListener {

@Override

publicvoid onClick(View v) {

。。。。。。

SAXParserFactory factory =SAXParserFactory.newInstance() ;

SAXParserparser = null ;

MySAX sax = new MySAX() ;

parser = factory.newSAXParser() ;

parser.parse(file,sax) ;

List<LinkMan>all = sax.getAll() ;

System.out.println(all.size());

MyDOMDemo.this.name.setText(all.get(0).getName());

MyDOMDemo.this.email.setText(all.get(0).getEmail());

}

}

}

4、XMLPull读取

步骤:

(1)创建XmlPullParseFactory -> XmlPullParse -> setInput()取得xml文件的XmlPullParse对象。

XmlPullParserFactory factory =XmlPullParserFactory.newInstance() ;

XmlPullParser xpp = factory.newPullParser() ;

xpp.setInput(this.input,"UTF-8") ;

(2)getEventType()取得事件码

(3)getName()取得元素标记名称

(4)getText()取得元素标记内的文字内容

(5)next()取得下一个事件码

//xml解析工具类

public classMyXMLPullUtil {

privateInputStream input = null ;

publicMyXMLPullUtil(InputStream input) {

this.input= input ;

}

publicList<LinkMan> getAllLinkMan() throws Exception{

List<LinkMan>all = null ;

LinkManman = null ;

String elementName = null;// 保存节点的名称

XmlPullParserFactory factory =XmlPullParserFactory.newInstance() ;

XmlPullParser xpp = factory.newPullParser() ;

xpp.setInput(this.input,"UTF-8") ;

int eventType = xpp.getEventType() ;// 取得事件码

while(eventType != XmlPullParser.END_DOCUMENT){// 不是文档底部

if(eventType == XmlPullParser.START_DOCUMENT){// 文档开始

all= new ArrayList<LinkMan>() ;

} else if (eventType == XmlPullParser.START_TAG){// 元素标记开始

elementName = xpp.getName();// 取得元素标记名称

if("linkman".equals(elementName)){

man= new LinkMan() ;

}

} else if (eventType == XmlPullParser.END_TAG){// 结束元素

elementName = xpp.getName();// 取得节点名称

if("linkman".equals(elementName)){

all.add(man);

man= null ;

}

} else if (eventType == XmlPullParser.TEXT){// 数据

if("name".equals(elementName)){

man.setName(xpp.getText()) ;

}else if ("email".equals(elementName)) {

man.setEmail(xpp.getText()) ;

}

}

eventType = xpp.next();// 取得下一个事件码

}

returnall ;

}

}

5、XMLPull存储

步骤:

(1)XmlPullParseFactory -> XmlSerializer->setOutput()

XmlPullParserFactory factory =XmlPullParserFactory.newInstance() ;

XmlSerializer xs = factory.newSerializer();

xs.setOutput(this.output,"UTF-8");

(2)

xs.startDocument("UTF-8",true);

xs.startTag(null,"addresslist");

(3)

xs.startTag(null,"linkman");

xs.startTag(null,"name");

xs.text(man.getName());

xs.endTag(null,"name");

xs.startTag(null,"email");

xs.text(man.getEmail());

xs.endTag(null,"email");

xs.endTag(null,"linkman");

(4)

xs.endTag(null,"addresslist");

xs.endDocument();

(5)

xs.flush();

//xml解析工具类

public classMyXMLPullUtil {

privateList<LinkMan> all = null;

privateOutputStream output = null;

publicMyXMLPullUtil(OutputStream output,List<LinkMan> all) {

this.output= output;

this.all= all;

}

publicvoid save() throws Exception {

XmlPullParserFactory factory =XmlPullParserFactory.newInstance();

XmlSerializer xs = factory.newSerializer();

xs.setOutput(this.output,"UTF-8");

xs.startDocument("UTF-8","addresslist");// 根元素

Iterator<LinkMan>iter = this.all.iterator();

while(iter.hasNext()) {

LinkManman = iter.next();

xs.startTag(null,"linkman");

}

xs.endTag(null,"addresslist");

xs.endDocument();

xs.flush();

}

}

猜你在找的XML相关文章