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>


當然你可以根據你需求,調整程序使得產生更好的輸出.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章