android sax parsing xml method
下面说明第一种解析sax解析方式:
SAX是一个解析速度快并且占用内存少的xml解析器,非常适合用于Android等移动设备。 SAX解析XML文件采用的是事件驱动,也就是说,它并不需要解析完整个文档,在按内容顺序解析文档的过程中,SAX会判断当前读到的字符是否合法XML语法中的某部分,如果符合就会触发事件。所谓事件,其实就是一些回调(callback)方法,这些方法(事件)定义在ContentHandler接口。下面是一些ContentHandler接口常用的方法:
startDocument() 当遇到文档的开头的时候,调用这个方法,可以在其中做一些预处理的工作。
endDocument() 和上面的方法相对应,当文档结束的时候,调用这个方法,可以在其中做一些善后的工作。
startElement(String namespaceURI, String localName, String qName, Attributes atts)
当读到一个开始标签的时候,会触发这个方法。namespaceURI就是命名空间,localName是不带命名空间前缀的标签名,qName是带命名空间前缀的标签名。通过atts可以得到所有的属性名和相应的值。要注意的是SAX中一个重要的特点就是它的流式处理,当遇到一个标签的时候,它并不会纪录下以前所碰到的标签,也就是说,在startElement()方法中,所有你所知道的信息,就是标签的名字和属性,至于标签的嵌套结构,上层标签的名字,是否有子元属等等其它与结构相关的信息,都是不得而知的,都需要你的程序来完成。这使得SAX在编程处理上没有DOM来得那么方便。
endElement(String uri, String localName, String name) 这个方法和上面的方法相对应,在遇到结束标签的时候,调用这个方法。
characters(char[] ch, int start, int length)
这个方法用来处理在XML文件中读到的内容,第一个参数为文件的字符串内容,后面两个参数是读到的字符串在这个数组中的起始位置和长度,使用new String(ch,start,length)就可以获取内容。
xml的源文件和android dom 解析xml方式中的xml 文件内容相同,可以参照那个文件来解析,只是名称不同而已,

这个途中图中有三个saxTest.xml文件,分别对应三种不同的读取方式
// 读取类得包下的xml文件 // InputStream inputStream = // this.getClass().getClassLoader().getResourceAsStream("cn/com/sax/saxTest.xml"); //读取src下xml文件 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("saxTest.xml"); // 读取assets下的xml文件 // InputStream inputStream = this.getAssets().open("saxTest.xml");第一种方式解析xml 主要是继承DefaultHandler,实现其中的几个方法
下面放出我解析的源码:
/**
* 用sax解析xml的第一种方式
* @return
*/
private String saxParse(){
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser;
String xmlStr = "第一种解析方式:\n";
try {
// 读取类得包下的xml文件
// InputStream inputStream =
// this.getClass().getClassLoader().getResourceAsStream("cn/com/sax/saxTest.xml");
//读取src下xml文件
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream("saxTest.xml");
// 读取assets下的xml文件
// InputStream inputStream = this.getAssets().open("saxTest.xml");
parser = factory.newSAXParser();
SaxParseHandler personHandler = new SaxParseHandler();
parser.parse(inputStream, personHandler);
xmlStr = xmlStr + personHandler.parseToString();
} catch (ParserConfigurationException e) {
e.printStackTrace();
Log.e("TEST", "" + e.toString());
} catch (SAXException e) {
e.printStackTrace();
Log.e("TEST", "" + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("TEST", "" + e.toString());
}
return xmlStr;
}继承DefaultHandler处理xml中的元素节点。
class SaxParseHandler extends DefaultHandler {
String result;
public String parseToString() {
return result;
}
String str = null;
/**
* xml开始时,执行此函数
*/
@Override
public void startDocument() throws SAXException {
// Log.e("TEST", "startDocument");
}
/**
* xml结束时,执行此函数
*/
@Override
public void endDocument() throws SAXException {
// Log.e("TEST", "endDocument");
}
/**
* xml标签开始时,执行此函数,读取标签名称,和标签内的属性
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("group".equals(localName)) {
String groupName = attributes.getValue(0);
String num = attributes.getValue(1);
result = result + "groupName=" + groupName + " num =" + num
+ "\n";
} else if ("person".equals(localName)) {
String personName = attributes.getValue(0);
String age = attributes.getValue(1);
// 和getValue(1)等效
// String txt = attributes.getValue("age");
result = result + "personName" + personName + " age=" + age
+ "\n";
} else {
str = localName;
}
// Log.e("TEST", "startElement");
}
/**
* xml标签结束时,执行此函数
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
str = null;
// Log.e("TEST", "endElement");
}
/**
* 解析标签内的值,如<chinese>ssss</chinese>,为了读取"ssss"
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (str != null) {
String data = new String(ch, start, length);
//xml文件格式化的时候容易产生以下换行,制表符等特殊字符,
//这些需要特别注意处理
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(data);
data = m.replaceAll("");
if ("chinese".equals(str)) {
if(!data.equals("")){
String chinese = data;
result = result + "chinese=" + chinese;
}
} else if ("english".equals(str)) {
if(!data.equals("")){
String english = data;
result = result + "english=" + english + "\n";
}
}
}
}
}
以上就是android sax解析 xml方式的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20443
7
13592
4
How to change the song cache directory in NetEase Cloud Music
Jan 13, 2026 am 10:30 AM
In the process of using NetEase Cloud Music, you occasionally need to adjust the song cache path, for example, if the original cache location is running out of disk space, or you want to store all cached files in a designated folder. The following will give you a clear explanation on how to modify the song cache path of NetEase Cloud Music. Launch the NetEase Cloud Music App on the Android system on the mobile phone. Click the "≡" three horizontal lines icon in the upper left corner to bring up the side menu bar. Swipe to find and click "Settings" in the sidebar. After entering the settings page, locate the "Storage Path" option. The cache folder currently displayed is the cache folder in use. Click "Storage Path", and the system will bring up the local file manager, allowing you to select any folder in the built-in storage of the fuselage, or a directory in the mounted SD card. select
Where to download the latest version of iMoutai? iMoutai official app safety installation guide
Jan 13, 2026 pm 04:42 PM
The official download entrance for the latest version of iMoutai v1.9.0 is the official website https://www.moutaichina.com/, which supports dual-end downloads for Android and iOS. The installation package is transmitted through SSL encryption and SHA256 verification to ensure security and trustworthiness.
What to do if the text layout of the Quark browser webpage is confusing? Quark browser page adaptation tutorial
Jan 15, 2026 pm 02:24 PM
When Quark Browser's web page layout is disordered, it can be repaired by enabling "Web Page Adaptation Optimization", disabling hardware acceleration, clearing font and CSS cache, switching the UA logo, and turning off script interception.
The Ultimate Guide to AI Photo Editing: Create Social Media Hits Easily
Jan 08, 2026 pm 06:54 PM
In today's age of social media, a striking photo can often determine your online presence. Do you also want to have a photo that can quickly attract attention and attract attention? Now, AI technology makes this easier than ever. This blog will give you an in-depth understanding of how to use AI tools, especially Google Gemini AI, to easily edit photos and create stunning
What to do if the cache of Zeus Browser takes up too much? Clean the cache of Zeus Browser
Jan 10, 2026 pm 12:36 PM
Zeus Browser runs slowly, the page loads abnormally, or a large amount of storage space is occupied, which is probably caused by the backlog of cache files. It can be cleaned through five methods: the main interface shortcut entry, privacy settings, traffic consumption module, system-level shortcut keys, or manually deleting the local cache directory.
How to use AI to color black and white photos AI old photo coloring tutorial
Jan 08, 2026 pm 12:51 PM
You can use the DeOldify online platform, Photoshop Beta version neural filter, Python to run the Colourful model locally, or the Remini mobile app to automatically color black and white old photos. Each method is suitable for ordinary users who do not need programming, professional designers, technical users who pay attention to privacy, and fast processing needs on the mobile terminal.
How to set the default QR code generation method in Win11_Win11 shared link automatic transcoding associated application [Tool]
Jan 10, 2026 pm 01:33 PM
It is necessary to enable the system QR code function through ViVeTool, set the default sharing to Windows sharing, the WiFi password can directly generate the QR code in the WLAN settings, and fix icon abnormalities caused by high contrast or third-party startup items.
Warp: AI-driven smart terminal improves your coding efficiency
Jan 06, 2026 pm 03:03 PM
In the ever-changing field of software development, developers need to continuously improve their skills in order to keep up with the pace of technological development. Traditional coding methods can no longer meet the needs of modern development, and the emergence of AI technology has brought new possibilities to developers. Warp is an AI-driven smart terminal that seamlessly integrates AI into your coding workflow, providing code generation, natural language interaction, and multi-threaded generation.




