java SAX使用范例

来源:互联网 发布:苹果7手机怎么备份数据 编辑:程序博客网 时间:2024/05/16 09:01
示例里使用的xml文件:books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>?
<book id="12">?
<name>thinking in java</name>?
<price>85.5</price>?
</book>?
<book id="15">?
<name>Spring in Action</name>?
<price>39.0</price>?
</book>?
</books>?

自定义Handler类:

package test;

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;

/**

* @author yuchao
*
*/
public class TestMyXmlHandler extends DefaultHandler {

private String currentValue = null;


@Override

public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
if ("book".equals(qName)) {
System.out.println("book id=" + attributes.getValue("id"));
} else if ("name".equals(qName)) {
System.out.print("??? name : ");
}else if ("price".equals(qName)) {
System.out.print("??? price : ");
}
}

@Override

public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if (currentValue != null) {
System.out.println(currentValue);
currentValue = null;
}
}

@Override

public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
currentValue = new String(ch, start, length);
}

/**

* @param args
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {

// TODO Auto-generated method stub
SAXParser parser=SAXParserFactory.newInstance().newSAXParser();
TestMyXmlHandler handler=new TestMyXmlHandler();
parser.parse(new File("conf/books.xml"),handler);

}


}


示例结果:

book id=12
name : thinking in java
price : 85.5


book id=15

name : Spring in Action
price : 39.0


原创粉丝点击