服务器之家

服务器之家 > 正文

21天学习android开发教程之XML解析与生成

时间:2021-05-26 15:32     来源/作者:aishu

本文使用SAX来解析XML,在Android里面可以使用SAX和DOM,DOM需要把整个XML文件读入内存再解析,比较消耗内存,而SAX基于事件驱动的处理方式,可以在各节点触发回调函数,不过SAX适合节点结构简单的XML文档,复杂的XML文档在后期的节点深度处理会有点麻烦。
本文要解析的test.xml文件如下:

?
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<test>
 <title>testSAX</title>
  <content aa="1" bb="2">
   <name>hellogv</name>
   <url>http://blog.csdn.net/hellogv</url>
  </content>
</test>

使用SAX解析,需要定义SAXParserFactory(使应用程序能够配置和获取基于 SAX 的解析器以解析 XML 文档),SAXParser(从各种输入源解析 XML),XMLReader(使用回调函数读取 XML 文档),其中XMLReader是个关键。XMLReader可以为解析XML定义各种回调函数,“条件符合”的时候触发这些回调函数。

?
1
2
3
4
5
6
SAXParserFactory factory = SAXParserFactory.newInstance();
                   SAXParser parser = factory.newSAXParser();
                   XMLReader reader = parser.getXMLReader();
                   reader.setContentHandler(handler);
                   reader.parse(new InputSource(testSAX.this.getResources()
                           .openRawResource(R.raw.test)));

在这段代码里,XMLReader就调用继承DefaultHandler的SAXHandler。DefaultHandler已实现ContentHandler, DTDHandler, EntityResolver, ErrorHandler等接口,包含常见读取XML的操作,具体请看下面的SAXHandler.java源码。
读取各节点之后,使用XmlSerializer重新组合并输出XML字符串。本文的main.xml代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 
    <button android:layout_height="wrap_content"
        android:layout_width="fill_parent" android:id="@+id/btnSAX"
        android:text="使用SAX解析XML">
    <button android:layout_height="wrap_content"
        android:layout_width="fill_parent" android:text="生成XML" android:id="@+id/btnOutput">
    <edittext android:text="@+id/EditText01" android:id="@+id/EditText01"
        android:layout_width="fill_parent" android:layout_height="fill_parent">

testSAX.java的源码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.testSAX;
 
import java.io.StringWriter;
 
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlSerializer;
 
import android.app.Activity;
import android.os.Bundle;
 
import android.util.Xml;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class testSAX extends Activity {
    /** Called when the activity is first created. */
    Button btnSAX, btnOutput;
    EditText memo;
    SAXHandler handler = new SAXHandler();
 
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnSAX = (Button) this.findViewById(R.id.btnSAX);
        btnSAX.setOnClickListener(new ClickEvent());
        btnOutput = (Button) this.findViewById(R.id.btnOutput);
        btnOutput.setOnClickListener(new ClickEvent());
        memo = (EditText) this.findViewById(R.id.EditText01);
 
    }
 
    class ClickEvent implements View.OnClickListener {
 
        @Override
        public void onClick(View v) {
            if (v == btnSAX) {//解析XML,并保存标记,属性等值
                try {
                    SAXParserFactory factory = SAXParserFactory.newInstance();
                    SAXParser parser = factory.newSAXParser();
                    XMLReader reader = parser.getXMLReader();
                    reader.setContentHandler(handler);
                    reader.parse(new InputSource(testSAX.this.getResources()
                            .openRawResource(R.raw.test)));
                } catch (Exception ee) {}
            }
            else if (v == btnOutput) {//生成XML
                try {
                    XmlSerializer serializer = Xml.newSerializer();
                    StringWriter writer = new StringWriter();
                    try {
                        serializer.setOutput(writer);
                        serializer.startDocument("UTF-8",true);
                        
                        for(int i=0;i<handler.getkeys().size();i++)
                        {
                            if(handler.GetKeys().get(i).equals("startTag"))
                            {
                                serializer.startTag("", (String) handler.GetValues().get(i));
                            }
                            else if(handler.GetKeys().get(i).equals("Attr")){
                                String[] str= (String[]) handler.GetValues().get(i);
                                serializer.attribute("",str[0],str[1]);
                            }
                            else if(handler.GetKeys().get(i).equals("text"))
                                serializer.text((String)handler.GetValues().get(i));
                            else if(handler.GetKeys().get(i).equals("endTag"))
                            {
                                serializer.endTag("", (String) handler.GetValues().get(i));
                            }
                        }
                        serializer.endDocument();
                        String text=writer.toString();
                        text=text.replace("><", ">/r/n<");
                        memo.setText(text);//输出到文本框
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    
                } catch (Exception e) {}
            }
 
        }
 
    }
}

 PS:服务器之家推荐一款在线XML格式化工具:https://tool.zzvips.com/t/xml/

以上就是本文的全部内容,希望对大家的学习有所帮助。

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部