search
HomeBackend DevelopmentXML/RSS TutorialAndroid pull parsing xml method

 pull解析xml文件,和sax和dom一样 都可以脱离android单独使用,pull和sax的原理一样,不一样的地方是pull读取xml文件后调用方法返回的是数字, 
   读取到xml的声明返回数字0 START_DOCUMENT; 
   读取到xml的结束返回数字1 END_DOCUMENT ; 
   读取到xml的开始标签返回数字2 START_TAG 
   读取到xml的结束标签返回数字3 END_TAG 
   读取到xml的文本返回数字4 TEXT 

   pull是开源的项目 源码下载地址http://www.php.cn/ 

被解析的xml文档和android dom 解析xml方式 中的xml文档一样,命名为pullTest.xml.

private String pullParseXml(InputStream inputStream) {
		String result = "";
		//解析全部的xml
		boolean isParse = true;
		try {
			// 创建一个xmlPullParser的工厂
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			// 获取一个解析实例
			XmlPullParser parse = factory.newPullParser();
			// 设置输入流的编码格式
			parse.setInput(inputStream, "UTF-8");
			// 当前事件的类型
			int eventType = parse.getEventType();
			while (XmlPullParser.END_DOCUMENT != eventType) {
				// 当前节点的名称
				String nodeName = parse.getName();
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if ("group".equals(nodeName)) {
						// 解析<group>节点中的属性值,getAttributeCount()获取属性的个数
						for (int i = 0; i < parse.getAttributeCount(); i++) {
							// 属性名称
							String groupName = parse.getAttributeName(i);
							// 属性名称对应的值
							String nameValue = parse.getAttributeValue(i);
							result = result + groupName + " = " + nameValue;
						}
						result += "\n";
					} else if ("person".equals(nodeName)) {
						String personName = parse.getAttributeValue(0);
						String age = parse.getAttributeValue(1);
						result = result + "personName = " + personName
								+ "age =" + age + "\n";
					} else if ("chinese".equals(nodeName)) {
						//节点对应的文本
						String chinese = parse.nextText();
						Pattern p = Pattern.compile("\\s*|\t|\r|\n");
						Matcher m = p.matcher(chinese);
						chinese = m.replaceAll("");

						result = result + "chinese = " + chinese;
					} else if ("english".equals(nodeName)) {
						String english = parse.nextText();

						Pattern p = Pattern.compile("\\s*|\t|\r|\n");
						Matcher m = p.matcher(english);
						english = m.replaceAll("");

						result = result + "english = " + english + "\n";
					}
					break;
				case XmlPullParser.END_TAG:
					//在解析到一个group节点完成时,退出解析xml文件
//					if("group".equals(nodeName)){
//						eventType = XmlPullParser.END_DOCUMENT; 
//						isParse = false;
//					}
					break;
				default:
					break;
				}
				//整个xml文件全部解析
				if(isParse){
					eventType = parse.next();
				}
			}
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

pull和sax不同最主要的体现在pull可以由客户随时终止解析xml.sax解析,只能从文档头一直读到尾,中间不能停止也不能对文件进行修改。直到解析完了整个文档才会返回。

//在解析到一个group节点完成时,退出解析xml文件
//					if("group".equals(nodeName)){
//						eventType = XmlPullParser.END_DOCUMENT; 
//						isParse = false;
//					}



只要满足退出解析的条件,只需要设置如下代码即可。

eventType = XmlPullParser.END_DOCUMENT;


pull解析方式用到的方法,大部分我都在代码中注释了。


 以上就是android  pull 解析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
Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

Building Feeds with XML: A Hands-On Guide to RSSBuilding Feeds with XML: A Hands-On Guide to RSSApr 14, 2025 am 12:17 AM

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

Creating RSS Documents: A Step-by-Step TutorialCreating RSS Documents: A Step-by-Step TutorialApr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

XML's Role in RSS: The Foundation of Syndicated ContentXML's Role in RSS: The Foundation of Syndicated ContentApr 12, 2025 am 12:17 AM

The core role of XML in RSS is to provide a standardized and flexible data format. 1. The structure and markup language characteristics of XML make it suitable for data exchange and storage. 2. RSS uses XML to create a standardized format to facilitate content sharing. 3. The application of XML in RSS includes elements that define feed content, such as title and release date. 4. Advantages include standardization and scalability, and challenges include document verbose and strict syntax requirements. 5. Best practices include validating XML validity, keeping it simple, using CDATA, and regularly updating.

From XML to Readable Content: Demystifying RSS FeedsFrom XML to Readable Content: Demystifying RSS FeedsApr 11, 2025 am 12:03 AM

RSSfeedsareXMLdocumentsusedforcontentaggregationanddistribution.Totransformthemintoreadablecontent:1)ParsetheXMLusinglibrarieslikefeedparserinPython.2)HandledifferentRSSversionsandpotentialparsingerrors.3)Transformthedataintouser-friendlyformatsliket

Is There an RSS Alternative Based on JSON?Is There an RSS Alternative Based on JSON?Apr 10, 2025 am 09:31 AM

JSONFeed is a JSON-based RSS alternative that has its advantages simplicity and ease of use. 1) JSONFeed uses JSON format, which is easy to generate and parse. 2) It supports dynamic generation and is suitable for modern web development. 3) Using JSONFeed can improve content management efficiency and user experience.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool