论坛首页 入门技术论坛

XML 文件的操作(五)

浏览 2127 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-01-08   最后修改:2009-01-08
XML:
<?xml version="1.0" encoding="gb2312"?>

<?xml-stylesheet type="text/xsl" href="students.xsl"?>

<students>
	<student sn="01">
		<name>张三</name>
		<age>18</age>
	</student>
	
	<student sn="02">
		<name>李四</name>
		<age>20</age>
	</student>
</students>

使用SAX读取XML文件:
package com.ibm.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
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;


/**
 * 使用SAX读取XML文件
 * @author Administrator
 *
 */
public class SAXPrinter extends DefaultHandler {

	/**
	 * 重新的方法
	 */
	public void startDocument() throws SAXException
	{
		System.out.println("<?xml version=\"1.0\" encoding='gb2312'?>");
	}
	
	/**
	 * 重新的方法
	 */
	public void processingInstruction(String target, String data) throws SAXException
	{
		System.out.println("<?"+target+" "+data+"?>");
	}
	
	/**
	 * 重新的方法
	 */
	public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException
	{
		System.out.print("<"+qName);
		int len=attrs.getLength();
		
		for(int i=0;i<len;i++)
		{
			System.out.print(" ");
			System.out.print(attrs.getQName(i));
			System.out.print("=\"");
			System.out.print(attrs.getValue(i));
			System.out.print("\"");
		}
		System.out.print(">");
	}
	
	/**
	 * 重新的方法
	 */
	public void characters(char[] ch, int start, int length) throws SAXException
	{
		System.out.print(new String(ch,start,length));
	}

	/**
	 * 重新的方法
	 */
	public void endElement(String uri, String localName, String qName) throws SAXException
	{
		System.out.print("</"+qName+">");
	}
	
	public static void main(String arge[]){
		SAXParserFactory spf=SAXParserFactory.newInstance();
		try
		{
			SAXParser sp=spf.newSAXParser();
			sp.parse(new File("students.xml"),new SAXPrinter());
		}
		catch (ParserConfigurationException e)
		{
			
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	}
	
}
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics