sax方式解析xml文件(asset文件和网络文件)

现在写了些博客后,变懒了!!!
1.在anddev.org上参考的一个例子: SaxParseXml.java文件
package cn.com;

import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SaxParseXml extends Activity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		/* Create a new TextView to display the parsingresult later. */
		TextView tv = new TextView(this);
		try {
			/* Create a URL we want to load some xml-data from. */
			//URL url = new URL(
					//"http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
			InputStream is = getAssets().open("dom.xml");
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();

			/* Create a new ContentHandler and apply it to the XML-Reader */
			ExampleHandler myExampleHandler = new ExampleHandler();

			xr.setContentHandler(myExampleHandler);

			/* Parse the xml-data from our URL. */
			//xr.parse(new InputSource(url.openStream()));
			xr.parse(new InputSource(is));
			   
			/* Parsing has finished. */

			/* Our ExampleHandler now provides the parsed data to us. */
			ParsedExampleDataSet parsedExampleDataSet = myExampleHandler
					.getParsedData();

			/* Set the result to be displayed in our GUI. */
			tv.setText(parsedExampleDataSet.toString());

		} catch (Exception e) {
			/* Display any Error to the GUI. */
			tv.setText("Error: " + e.getMessage());
		}
		/* Display the TextView. */
		this.setContentView(tv);
	}
}


2. ExampleHandler.java主要承担xml的解析工作
package cn.com;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ExampleHandler extends DefaultHandler {

	// ===========================================================
	// Fields
	// ===========================================================

	private boolean in_outertag = false;
	private boolean in_innertag = false;
	private boolean in_mytag = false;

	private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public ParsedExampleDataSet getParsedData() {
		return this.myParsedExampleDataSet;
	}

	// ===========================================================
	// Methods Receive notification of the beginning of the document
	// ===========================================================
	@Override
	public void startDocument() throws SAXException {
		this.myParsedExampleDataSet = new ParsedExampleDataSet();
	}

	@Override
	public void endDocument() throws SAXException {
		// Nothing to do
	}

	// Gets be called on opening tags like: <tag> Can provide attribute(s), when
	// xml was like: <tag attribute="attributeValue">
	//
	@Override
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		if (localName.equals("outertag")) {
			this.in_outertag = true;
		} else if (localName.equals("innertag")) {
			this.in_innertag = true;
		} else if (localName.equals("mytag")) {
			this.in_mytag = true;
		} else if (localName.equals("tagwithnumber")) {
			// Extract an Attribute
			String attrValue = atts.getValue("thenumber");
			int i = Integer.parseInt(attrValue);
			myParsedExampleDataSet.setExtractedInt(i);
		}
	}

	/**
	 * Gets be called on closing tags like: </tag>
	 */
	@Override
	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (localName.equals("outertag")) {
			this.in_outertag = false;
		} else if (localName.equals("innertag")) {
			this.in_innertag = false;
		} else if (localName.equals("mytag")) {
			this.in_mytag = false;
		} else if (localName.equals("tagwithnumber")) {
			// Nothing to do here
		}
	}

	// Gets be called on the following structure: <tag>characters</tag>

	@Override
	public void characters(char ch[], int start, int length) {
		if (this.in_mytag) {
			//myParsedExampleDataSet.setFirstTag(new String(ch, start, length));
		}

		if (this.in_mytag) {
			myParsedExampleDataSet.setExtractedString(new String(ch, start,
					length));
		}
	}
}


3. ParsedExampleDataSet.java将解析出的内容复制到比如一个对象属性上
package cn.com;

public class ParsedExampleDataSet {
	private String extractedString = null;
	private int extractedInt = 0;

	public String getExtractedString() {
		return extractedString;
	}

	public void setExtractedString(String extractedString) {
		this.extractedString = extractedString;
	}
	
	//public void setFirstTag(String ){
		
	//}

	public int getExtractedInt() {
		return extractedInt;
	}

	public void setExtractedInt(int extractedInt) {
		this.extractedInt = extractedInt;
	}

	public String toString() {
		return "ExtractedString = " + this.extractedString + "nExtractedInt = "
				+ this.extractedInt;
	}
}



4.测试的xml文件

<?xml version="1.0" encoding="utf-8"?>
<outertag>
	<innertag sampleattribute="innertagAttribute">
		<mytag>anddev.org    gfgf</mytag>
		<tagwithnumber thenumber="1220"/>
	</innertag>
</outertag>

你可能感兴趣的:(java,xml,.net,android,OS)