XML小練習:利用SAX解析XML文檔(感覺不方便)

XML文檔:
<?xml version="1.0" encoding="utf-8"?>
<學生名冊 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="student.xsd">
	<!-- 這不是演習,這不是演習 -->
	<學生 學號="1">
		<姓名>張三</姓名>
		<性別>男</性別>
		<年齡>20</年齡>
	</學生>
	<學生 學號="2">
		<姓名>李四</姓名>
		<性別>女</性別>
		<年齡>19</年齡>
	</學生>
	<學生 學號="3">
		<姓名>王五</姓名>
		<性別>男</性別>
		<年齡>21</年齡>
	</學生>
</學生名冊>



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

JAVA實現:

package com.xml.sax;

import java.io.File;
import java.util.Stack;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

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

public class Saxtest2 {
	public static void main(String[] args) throws Exception {
		SAXParserFactory factory = SAXParserFactory.newInstance();

		SAXParser parser = factory.newSAXParser();

		parser.parse(new File("student.xml"), new MyHandler2());
	}
}

class MyHandler2 extends DefaultHandler {

	private Stack<String> stack = new Stack<String>();

	private String name;

	private String sex;

	private String age;

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		stack.push(qName);// qName = Qualified Name 元素名稱

		for (int i = 0; i < attributes.getLength(); i++) {
			String attrName = attributes.getQName(i);
			String attrValue = attributes.getValue(i);

			System.out.println(attrName + "=" + attrValue);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String tag = stack.peek();

		if (tag.equals("姓名")) {
			name = new String(ch, start, length);
		} else if (tag.equals("性別")) {
			sex = new String(ch, start, length);
		} else if (tag.equals("年齡")) {
			age = new String(ch, start, length);
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		stack.pop();

		if (qName.equals("學生")) {
			System.out.println("姓名:" + name);
			System.out.println("性別:" + sex);
			System.out.println("年齡:" + age);
			System.out.println();
		}
	}
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章