本文使用SAX来解析XML,在Android里面可以使用SAX和DOM两种方法来解析XML,DOM方法需要把整个XML文件读入内存再解析,比较消耗内存,而SAX基于事件驱动的处理方式,可以在各节点触发回调函数,不过SAX适合节点结构简单的XML文档,复杂的XML文档在后期的节点深度处理会有点麻烦。
本文要解析的test.xml文件如下:
1
2
3
4
5
6
7
8
|
<
test
>
title
>testSAX</
>
content
aa
"1"
bb
"2"
>
name
>hellogv</
>
</
content
>
>
|
解析如上XML的结果图如下:
使用SAX解析,需要定义SAXParserFactory(使应用程序能够配置和获取基于 SAX 的解析器以解析 XML 文档),SAXParser(从各种输入源解析 XML),XMLReader(使用回调函数读取 XML 文档),其中XMLReader是个关键。XMLReader可以为解析XML定义各种回调函数,“条件符合”的时候触发这些回调函数。
@H_404_33@
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源码。
生成XML的结果如下:
上图是读取各节点之后,使用XmlSerializer重新组合并输出XML字符串。
main.xml代码:
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
xmlns:android
"http://schemas.android.com/apk/res/android"
android:orientation
"vertical"
android:layout_width
"fill_parent"
android:layout_height
"fill_parent"
Button
android:id
"@+id/btnSAX"
"fill_parent"
"wrap_content"
android:text
"使用SAX解析xml"
/>
Button
"@+id/btnOutput"
"fill_parent"
"wrap_content"
"生成xml"
/>
EditText
"@+id/EditText01"
"fill_parent"
"fill_parent"
"@+id/EditText01"
/>
import
java.util.ArrayList;
org.xml.sax.Attributes;
org.xml.sax.SAXException;
org.xml.sax.helpers.DefaultHandler;
android.util.Log;
public
class
SAXHandler
extends
DefaultHandler {
ArrayList<Object> values =
ArrayList<Object>();
// 保存值
@Override
void
startDocument()
throws
SAXException {
super
.startDocument();
}
@Override
endDocument()
SAXException {
.endDocument();
}
@Override
startElement(String uri,String localName,String qName,
Attributes attributes)
SAXException {
// 保存开始标记
keys.add(
"startTag"
);
values.add(localName);
Log.e(
,localName);
// 保存属性值
for
(
int
i =
0
; i < attributes.getLength(); i++) {
"Attr"
);
String[] str =
String[
2
];
str[
] = attributes.getLocalName(i);
1
] = attributes.getValue(i);
values.add(str);
] +
"="
+ str[
]);
}
}
@Override
endElement(String uri,String qName)
SAXException {
// 保存结束标记
"endTag"
);
values.add(localName);
}
@Override
characters(
char
[] ch,
start,monospace!important; font-size:1em!important; min-height:inherit!important">length)
SAXException {
String value =
String(ch,start,length);
value = value.trim();
if
(value.length() ==
)
return
;
"text"
);
values.add(value);
}
public
ArrayList<String> GetKeys() {
keys;
}
ArrayList<Object> GetValues() {
values;
}
}
testSAX.java代码:
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
javax.xml.parsers.SAXParser;
javax.xml.parsers.SAXParserFactory;
org.xml.sax.InputSource;
org.xml.sax.XMLReader;
org.xmlpull.v1.XmlSerializer;
android.app.Activity;
android.os.Bundle;
android.util.Xml;
android.view.View;
android.widget.Button;
android.widget.EditText;
testSAX
Activity {
/** Called when the activity is first created. */
Button btnSAX,btnOutput;
EditText memo;
SAXHandler handler =
SAXHandler();
@Override
onCreate(Bundle savedInstanceState) {
.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSAX = (Button)
.findViewById(R.id.btnSAX);
btnSAX.setOnClickListener(
ClickEvent());
btnOutput = (Button)
.findViewById(R.id.btnOutput);
btnOutput.setOnClickListener(
ClickEvent());
memo = (EditText)
.findViewById(R.id.EditText01);
}
ClickEvent
implements
View.OnClickListener {
@Override
onClick(View v) {
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(handler);
.getResources()
.openRawResource(R.raw.test)));
}
catch
(Exception ee) {
}
{
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer =
StringWriter();
{
serializer.setOutput(writer);
serializer.startDocument(
"UTF-8"
true
);
; i < handler.GetKeys().size(); i++) {
(handler.GetKeys().get(i).equals(
)) {
serializer.startTag(
""
.GetValues().get(i));
)) {
String[] str = (String[]) handler.GetValues()
.get(i);
serializer.attribute(
],monospace!important; font-size:1em!important; min-height:inherit!important">]);
))
serializer.text((String) handler.GetValues()
.get(i));
)) {
serializer.endTag(
.GetValues().get(i));
}
}
serializer.endDocument();
String text = writer.toString();
text = text.replace(
"><"
">/r/n<"
);
memo.setText(text);
// 输出到文本框
(Exception e) {
throw
RuntimeException(e);
}
(Exception e) {
}
}
}
}
}