search
HomeBackend DevelopmentXML/RSS Tutorialandroid sax parsing xml method

android sax parsing xml method

Feb 17, 2017 pm 03:12 PM

下面说明第一种解析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中文网(www.php.cn)!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding RSS: An XML PerspectiveUnderstanding RSS: An XML PerspectiveApr 25, 2025 am 12:14 AM

RSS is an XML-based format used to publish frequently updated content. 1. RSSfeed organizes information through XML structure, including title, link, description, etc. 2. Creating RSSfeed requires writing in XML structure, adding metadata such as language and release date. 3. Advanced usage can include multimedia files and classified information. 4. Use XML verification tools during debugging to ensure that the required elements exist and are encoded correctly. 5. Optimizing RSSfeed can be achieved by paging, caching and keeping the structure simple. By understanding and applying this knowledge, content can be effectively managed and distributed.

RSS in XML: Decoding Tags, Attributes, and StructureRSS in XML: Decoding Tags, Attributes, and StructureApr 24, 2025 am 12:09 AM

RSS is an XML-based format used to publish and subscribe to content. The XML structure of an RSS file includes a root element, an element, and multiple elements, each representing a content entry. Read and parse RSS files through XML parser, and users can subscribe and get the latest content.

XML's Advantages in RSS: A Technical Deep DiveXML's Advantages in RSS: A Technical Deep DiveApr 23, 2025 am 12:02 AM

XML has the advantages of structured data, scalability, cross-platform compatibility and parsing verification in RSS. 1) Structured data ensures consistency and reliability of content; 2) Scalability allows the addition of custom tags to suit content needs; 3) Cross-platform compatibility makes it work seamlessly on different devices; 4) Analytical and verification tools ensure the quality and integrity of the feed.

RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software