SAX解析XML file

[list]
[*]1. SAX简述
[*]2. SAX in practice
[/list]

1.SAX简述:
SAX全称Simple API for XML, 用于简单并快速的解析XML文件,是基于事件处理的模型,SUN定义了规范,常用的主要接口包括ContentHandler, ErrorHanlder, XMLReader, XMLFilter, Attributes, InputSource, Locator, 及不常用的EntityResolver, DTDHandler, LexicalHandler, DeclHandler等, UML静态类图如下:
[img]/upload/attachment/98386/dbf5d6ff-b162-3750-b510-ee5591de4b3b.gif[/img], 也许读者会问,这么多接口都要去实现,并且,很多接口中的方法并不是所要的,那岂不是做无用功, 放心,其中有一个DefaultHanlder已经适配了所有的重要的接口,你只需要继承DefaultHandler并重写你所想处理的方法即可,比如startElement, endElement, charactors等。

其中Apache下的Xerces(http://sax.sourceforge.net/)对这些接口有个集体的实现.
2.SAX in practice

被解析的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<books>
<book pages="1000" price="$99">
<name>Thinking in java</name>
<version>3.0</version>
</book>
<book pages="800" price="$40">
<name>JUnit in Action</name>
<version>2.0</version>
</book>
<book pages="900" price="$70">
<name>Lucene in Action</name>
<version>2.0</version>
</book>
</books>


解析代码如下:

package com.chris.sax.action;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;


import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class XMLParser
{
//handler normal info.
protected PrintStream output =
new PrintStream( new BufferedOutputStream( new FileOutputStream( java.io.FileDescriptor.out ), 128 ), true );
//handler error info.
protected PrintStream error =
new PrintStream( new BufferedOutputStream( new FileOutputStream( java.io.FileDescriptor.err ), 128 ), true );

public void parserXMLFile(String fileName ) throws SAXException, IOException
{
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler( new MyContentHandler() );
reader.setErrorHandler( new MyErrorHandler() );
InputSource source = new InputSource( new FileInputStream( new File( fileName ) ) );
reader.parse(source);
}

class MyErrorHandler implements ErrorHandler
{

public void error( SAXParseException exception ) throws SAXException
{

error.println( exception.getMessage() );
}

public void fatalError( SAXParseException exception ) throws SAXException
{

error.println( exception.getMessage() );
}

public void warning( SAXParseException exception ) throws SAXException
{
output.println( exception.getMessage() );

}

}
class MyContentHandler implements ContentHandler
{


public void characters( char[] ch, int start, int length )
throws SAXException
{
output.print(ch);
}

public void endDocument() throws SAXException
{

}

public void endElement( String uri, String localName, String name )
throws SAXException
{

output.println("</"+localName+">");

}

public void endPrefixMapping( String prefix ) throws SAXException
{


}

public void ignorableWhitespace( char[] ch, int start, int length )
throws SAXException
{

}

public void processingInstruction( String target, String data )
throws SAXException
{

}

public void setDocumentLocator( Locator locator )
{

}

public void skippedEntity( String name ) throws SAXException
{

}

public void startDocument() throws SAXException
{
output.println("<xml version=\"1.0\" encoding=\"utf-8\"?>");
}

public void startElement( String uri, String localName, String name,
Attributes atts ) throws SAXException
{
//uri is identifier of namespace
//name-->prefix:localName
output.print("<" +localName );
for( int i = 0; i < atts.getLength(); i++ )
{
String attrName = atts.getLocalName( i );
String attrValue = atts.getValue( i );
output.print(" " + attrName + "=" + attrValue );
}
output.print(">");

}

public void startPrefixMapping( String prefix, String uri )
throws SAXException
{

}
}

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

XMLParser parser = new XMLParser();
parser.parserXMLFile("books.xml");
}
}



解析后的结果如下:

<xml version="1.0" encoding="utf-8"?>
<books>
<books>
<book pages="1000" price="$99">
<name>Thinking in java</name>
<version>3.0</version>
</book>
<book pages="800" price="$40">
<name>JUnit in Action</name>
<version>2.0</version>
</book>
<book pages="900" price="$70">
<name>Lucene in Action</name>
<version>2.0</version>
</book>
</books>
<books>
<book pages="1000" price="$99">
<name>Thinking in java</name>
<version>3.0</version>
</book>
<book pages="800" price="$40">
<name>JUnit in Action</name>
<version>2.0</version>
</book>
<book pages="900" price="$70">
<name>Lucene in Action</name>
<version>2.0</version>
</book>
</books>


这样就把XML文件大体输出到屏幕上来了, 但是你会发现,这些不是你真正想要的结果,甚至出现了乱码,原因就在于characters可能被多次调用,甚至次数不定, 以下是个改进的版本

package com.chris.sax.action;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;


import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class XMLParser
{
//handler normal info.
protected PrintStream output =
new PrintStream( new BufferedOutputStream( new FileOutputStream( java.io.FileDescriptor.out ), 128 ), true );
//handler error info.
protected PrintStream error =
new PrintStream( new BufferedOutputStream( new FileOutputStream( java.io.FileDescriptor.err ), 128 ), true );

public void parserXMLFile(String fileName ) throws SAXException, IOException
{
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler( new MyContentHandler() );
reader.setErrorHandler( new MyErrorHandler() );
InputSource source = new InputSource( new FileInputStream( new File( fileName ) ) );
reader.parse(source);
}

class MyErrorHandler implements ErrorHandler
{

public void error( SAXParseException exception ) throws SAXException
{

error.println( exception.getMessage() );
}

public void fatalError( SAXParseException exception ) throws SAXException
{

error.println( exception.getMessage() );
}

public void warning( SAXParseException exception ) throws SAXException
{
output.println( exception.getMessage() );

}

}
class MyContentHandler implements ContentHandler
{

private StringBuffer buffer = new StringBuffer();
private String key;


public void characters( char[] ch, int start, int length )
throws SAXException
{
buffer.append( ch, start, length);

}

public void endDocument() throws SAXException
{

}

public void endElement( String uri, String localName, String name )
throws SAXException
{

if( key.equals( localName))
{
output.print(buffer);
}

output.print("</"+localName+">");



}

public void endPrefixMapping( String prefix ) throws SAXException
{


}

public void ignorableWhitespace( char[] ch, int start, int length )
throws SAXException
{

}

public void processingInstruction( String target, String data )
throws SAXException
{

}

public void setDocumentLocator( Locator locator )
{

}

public void skippedEntity( String name ) throws SAXException
{

}

public void startDocument() throws SAXException
{
output.println("<xml version=\"1.0\" encoding=\"utf-8\"?>");
}

public void startElement( String uri, String localName, String name,
Attributes atts ) throws SAXException
{
//uri is identifier of namespace
//name-->prefix:localName

buffer.delete(0, buffer.length());
key = localName;

output.print("<" +localName );
for( int i = 0; i < atts.getLength(); i++ )
{
String attrName = atts.getLocalName( i );
String attrValue = atts.getValue( i );
output.print(" " + attrName + "=" + attrValue );
}
output.print(">");

}

public void startPrefixMapping( String prefix, String uri )
throws SAXException
{

}
}

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

XMLParser parser = new XMLParser();
parser.parserXMLFile("books.xml");
}
}


输出结果如下:
<xml version="1.0" encoding="utf-8"?>
<books><book pages=1000 price=$99><name>Thinking in java</name><version>3.0</version></book><book pages=800 price=$40><name>JUnit in Action</name><version>2.0</version></book><book pages=900 price=$70><name>Lucene in Action</name><version>2.0</version></book></books>


当然你可以根据你需求,调整程序使得产生更好的输出.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值