移动端_IOS【Android基础入门〖16〗】XML解析

====================================================================================================================================

Sax 解析之初见:

1,准备一个books.xml 内容可以在下文看到,我的目的就是解析它并在屏幕上打印出来。

2,新建一个book 类 ,其属性 (id,name,price,publisher)  与 books.xml 里面的的标签  (id,name,price,publisher)  相一致。为了简单容易理解的获取books.xml里面的数据。           当然,并不是必须的,只是为了赋值方便,通俗易懂。

3,实现一个处理器 class SaxParseXml extends DefaultHandler  。

      a, 在 DefaultHandler 中重写了 startDocument ,用于开始解析 books.xml,可以在此新建一个List<Book>,以便获取各个book对象数据。 

      b, 在 startElement     中开始解析 books.xml中 的元素 ,例如,每次 解析到 id 或者 name 时 都会触发一次 characters 进行解析,在characters 中 将获得数据 赋值给 book               类,从而得到数据,

      c, endElement 结束一个元素(标签)的解析,将book对象加入List<Book>。

      d, 在endDocument 中结束对 books.xml的解析。

4,在MainActivity 中 

InputStream stream =getAssets().open("books.xml");
SAXParser parser=SAXParserFactory.newInstance().newSAXParser();
SaxParseXml parsexml=new SaxParseXml();
parser.parse(stream,parsexml);
读取books.xml进入 输入流对象 stream

新建一个解析器对象 parser 

实例化自己的处理器 parsexml

通过parser.parse(stream,parsexml) 实现用我们自己的处理器来解析xml

====================================================================================================================================

Dom 解析之初见:

根据资料可以知道Dom解析将booksxml文件加载进内存中再进行遍历xml节点获取数据。基本的步骤大致如下:

1,  创建一个 文档构造器 

	DocumentBuilder documentbuider = DocumentBuilderFactory.newInstance().newDocumentBuilder();//用来获取 xml 数据流。


2, 将获得 xm l数据流赋值给Document 文档对象document。

	Document document = documentbuider.parse(stream);

3, 获取 xml 的 所有节点,并获取根节点

	Element element = document.getDocumentElement(); 
	NodeList booknodes = element.getElementsByTagName("book");

4,    遍历根节点,从每一个根节点中获得该根节点的所有子节点,再遍历该根节点的所有子节点,即两个嵌套循环。

		Element element = document.getDocumentElement();
		NodeList booknodes = element.getElementsByTagName("book");//获取所有根节点
		
		for(int i =0; i < booknodes.getLength(); i++){
			
			Element bookelement = (Element)booknodes.item(i);
			Book book = new Book();
			
			NodeList childnodes = bookelement.getChildNodes();//获取该根节点的所有子节点
			for(int j=0;j<childnodes.getLength();j++){
				if(childnodes.item(j).getNodeType() == Node.ELEMENT_NODE){
					if("id".equals(childnodes.item(j).getNodeName())){
						book.id=childnodes.item(j).getFirstChild().getNodeValue();//获取数据
					}
					else if("name".equals(childnodes.item(j).getNodeName())){
						book.name=childnodes.item(j).getFirstChild().getNodeValue();
					}
					else if("price".equals(childnodes.item(j).getNodeName())){
						book.price=childnodes.item(j).getFirstChild().getNodeValue();
					}
					else if("publisher".equals(childnodes.item(j).getNodeName())){
						book.publisher=childnodes.item(j).getFirstChild().getNodeValue();
					}					
				}
			}
			list.add(book);
		}

====================================================================================================================================

Pull 解析之初见:

在我查阅所有的资料中,有一句话最为贴切:

Pull解析与Sax解析很是接近,区别在于:Sax解析从进行到结束不受自己控制,属于把所有数据硬塞给你;Pull解析则不同,每解析一个book 都将需要手动 转到下一个解析事件,属于自己去要。

基本的步骤大致如下:

1,  创建一个 pull 解析器实例,并获取 xml 数据流,同时设置字符编码为 “UTF-8”

XmlPullParser pullparse = XmlPullParserFactory.newInstance().newPullParser();
			pullparse.setInput(stream, "UTF-8");

2,  获得 pull 解析需要的事件类型,因为触发下一次xml解析需要自己手动进行

int eventype = pullparse.getEventType();

3,  遍历每一个事件类型,进行相应的解析操作

List<Book> books = null;
Book book = null;
			
while(XmlPullParser.END_DOCUMENT!=eventype){
				
				String str = pullparse.getName();
				switch (eventype) {
				case XmlPullParser.START_DOCUMENT:
					books = new ArrayList<Book>();
					break;
					
                case XmlPullParser.START_TAG:  
                    if(str.equals("book")){  
                        book = new Book();  
                    }
                    else if(str.equals("id")){  
                    	book.id=pullparse.nextText();  
                    }
                    else if(str.equals("name")){  
                    	book.name=pullparse.nextText();  
                    }  
                    else if(str.equals("price")){  
                    	book.price=pullparse.nextText();  
                    }  
                    else if(str.equals("publisher")){  
                    	book.publisher=pullparse.nextText();  
                    }
                    break;  
                  
                case XmlPullParser.END_TAG:  
                    if(str.equals("book")&&book!=null){  
                    	books.add(book);  
                    }                        
                    break; 
				default:
					break;
				}
				eventype = pullparse.next();				
			}			

====================================================================================================================================

具体代码实现如下:


目录结构:



第一步: Books.xml

<?xml version="1.0" encoding="utf-8"?>
<books>
	<book>
		<id>1001</id>
		<name>Thinking In Java</name>
		<price>80.00</price>
		<publisher>人民邮电出版社</publisher>
	</book>
	<book>
		<id>1002</id>
		<name>Python核心编程</name>
		<price>89.00</price>
		<publisher>宝哥出版社</publisher>
	</book>
	<book>
		<id>1003</id>
		<name>C++程序设计语言</name>
		<price>99.00</price>
		<publisher>机械工业出版社</publisher>
	</book>
	<book>
		<id>1004</id>
		<name>HTML5</name>
		<price>35.00</price>
		<publisher>Matt出版社</publisher>
	</book>
	<book>
		<id>1005</id>
		<name>JavaScript高级编程</name>
		<price>85.00</price>
		<publisher>清华大学出版社</publisher>
	</book>
		<book>
		<id>1006</id>
		<name>C++沉思录</name>
		<price>91.00</price>
		<publisher>苏州职业大学出版社</publisher>
	</book>
</books>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="false"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2000"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:maxLines="22"
            android:scrollbars="vertical"
            android:text="@string/hello_world"
            tools:context=".MainActivity" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/bt_sax"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="@string/sax_parse" />
        <Button
            android:id="@+id/bt_dom"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="@string/dom_parse" />
        <Button
            android:id="@+id/bt_pull"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="@string/pull_parse" />
    </LinearLayout>
</LinearLayout>


第二步:Book.java

package com.example.matt;

public class Book {
	public String id;
	public String name;
	public String price;
	public String publisher;

}

第三步:SaxParseXml.java

package com.example.matt;

import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxParseXml extends DefaultHandler {

	public List<Book> list;
	public Book book;
	public String str;

	public void startDocument() throws SAXException {
		list = new ArrayList<Book>();

	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equals("book")) {
			book = new Book();
		}
		this.str = qName;

	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals("book")) {
			this.list.add(book);
		}
		this.str = null;
	}

	public void endDocument() throws SAXException {

	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {

		if (this.str != null) {
			String data = new String(ch, start, length);
			if (this.str.equals("id")) {
				this.book.id = data;
			} else if (this.str.equals("name")) {
				this.book.name = data;
			} else if (this.str.equals("price")) {
				this.book.price = data;
			} else if (this.str.equals("publisher")) {
				this.book.publisher = data;
			}

		}

	}

}


第四步:DomParseXml.java

package com.example.matt;

import android.annotation.SuppressLint;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@SuppressLint("ParserError")
public class DomParseXml {

	@SuppressLint("ParserError")
	public List<Book>getbooks(InputStream stream) throws Exception{
		List<Book>list = new ArrayList<Book>();
		DocumentBuilder documentbuider = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document document = documentbuider.parse(stream);
		
		Element element = document.getDocumentElement();
		
		NodeList booknodes = element.getElementsByTagName("book");
		
		for(int i =0; i < booknodes.getLength(); i++){
			
			Element bookelement = (Element)booknodes.item(i);
			Book book = new Book();
			
			NodeList childnodes = bookelement.getChildNodes();
			for(int j=0;j<childnodes.getLength();j++){
				if(childnodes.item(j).getNodeType() == Node.ELEMENT_NODE){
					if("id".equals(childnodes.item(j).getNodeName())){
						book.id=childnodes.item(j).getFirstChild().getNodeValue();
					}
					else if("name".equals(childnodes.item(j).getNodeName())){
						book.name=childnodes.item(j).getFirstChild().getNodeValue();
					}
					else if("price".equals(childnodes.item(j).getNodeName())){
						book.price=childnodes.item(j).getFirstChild().getNodeValue();
					}
					else if("publisher".equals(childnodes.item(j).getNodeName())){
						book.publisher=childnodes.item(j).getFirstChild().getNodeValue();
					}					
				}
			}
			list.add(book);
		}
		stream.close();
		return list;
		
	}

}


第五步:PullParseXml.java
package com.example.matt;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class PullParseXml {

		public List<Book>getbooks(InputStream stream) throws Exception{
			
			XmlPullParser pullparse = XmlPullParserFactory.newInstance().newPullParser();
			pullparse.setInput(stream, "UTF-8");
			
			int eventype = pullparse.getEventType();
		    List<Book> books = null;
			Book book = null;
			
			while(XmlPullParser.END_DOCUMENT!=eventype){
				
				String str = pullparse.getName();
				switch (eventype) {
				case XmlPullParser.START_DOCUMENT:
					books = new ArrayList<Book>();
					break;
					
                case XmlPullParser.START_TAG:  
                    if(str.equals("book")){  
                        book = new Book();  
                    }
                    else if(str.equals("id")){  
                    	book.id=pullparse.nextText();  
                    }
                    else if(str.equals("name")){  
                    	book.name=pullparse.nextText();  
                    }  
                    else if(str.equals("price")){  
                    	book.price=pullparse.nextText();  
                    }  
                    else if(str.equals("publisher")){  
                    	book.publisher=pullparse.nextText();  
                    }
                    break;  
                  
                case XmlPullParser.END_TAG:  
                    if(str.equals("book")&&book!=null){  
                    	books.add(book);  
                    }                        
                    break; 
				default:
					break;
				}
				eventype = pullparse.next();				
			}			
			stream.close();
			return books;
		}
}

第六步:MainActivity.java

package com.example.matt;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import android.os.Bundle;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	public int back_count = 1;
	public Button bt_sax;
	public Button bt_dom;
	public Button bt_pull;
	public InputStream stream;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		back_count = 1;

		bt_sax = (Button) findViewById(R.id.bt_sax);
		bt_dom = (Button) findViewById(R.id.bt_dom);
		bt_pull = (Button) findViewById(R.id.bt_pull);
		
		bt_sax.setOnClickListener(bt_listener);
		bt_dom.setOnClickListener(bt_listener);
		bt_pull.setOnClickListener(bt_listener);

	}

	public OnClickListener bt_listener = new OnClickListener() {
		public void onClick(View v) {
			TextView text = (TextView) findViewById(R.id.text);
			text.setMovementMethod(ScrollingMovementMethod.getInstance());
			List<Book> books=null;

			try {
				stream = getAssets().open("books.xml");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			switch (v.getId()) {
			case R.id.bt_sax:
				try {

					SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
					SaxParseXml saxparse = new SaxParseXml();
					parser.parse(stream, saxparse);
					stream.close();
					books = saxparse.list;
					String str = "";
					for (Book book : books) {
						str += ">>>id:" + book.id + "\n>>>name:" + book.name
								+ "\n>>>price:" + book.price + "\n>>>publisher:"
								+ book.publisher + "\n\n";
					}
					text.setText("Sax解析:\n"+str);

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FactoryConfigurationError e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
				
			case R.id.bt_dom:
				DomParseXml domparse = new DomParseXml();
				try {
					books = domparse.getbooks(stream);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String str = "";
				for (Book book : books) {
					str += "---id:" + book.id + "\n---name:" + book.name
							+ "\n---price:" + book.price + "\n---publisher:"
							+ book.publisher + "\n\n";

				}
				text.setText("Dom解析:\n"+str);
				break;
				
			case R.id.bt_pull:
				PullParseXml pullparse = new PullParseXml();
				try {
					books = pullparse.getbooks(stream);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String booklist = "";
				for (Book book : books) {
					booklist += "***id:" + book.id + "\n***name:" + book.name
							+ "\n***price:" + book.price + "\n***publisher:"
							+ book.publisher + "\n\n";

				}
				text.setText("Pull解析:\n"+booklist);
				break;
			}

		}

	};

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (back_count == 1) {
				Toast.makeText(this, "再按一次退出", 2000).show();
				back_count++;
			} else if (back_count == 2) {
				finish();

			}

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

}



运行效果:




That's all .

转载请注明出处!