XML 文件的操作(五)

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();
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值