Пример использования SAX-парсера на Java
В статье про SAX-парсер я рассказал что это такое и пообещал привести примеры не только на Visual Basic, но и на других языках программирования, в частности на Java. Ниже приведен такой пример - класс VXMLChecker, который умеет проверять XML-текст и XML-файл на соответствие XSD-схеме. Для этого у него есть два публичных метода: checkXML и checkFile.
package VXMLParseUtils;
/**
*
* @author Vitaly (http://blog.coolsoftware.ru/)
*/
import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.Locator;
import org.xml.sax.Attributes;
import org.xml.sax.XMLReader;
public class VXMLChecker extends DefaultHandler {
boolean m_bOutLog;
Locator m_Locator;
String m_sErrorString;
public VXMLChecker() {
m_bOutLog = true;
m_Locator = null;
m_sErrorString = “”;
}
////////////////////////////////////////////////////////////////////
// content handlers
////////////////////////////////////////////////////////////////////
public void setDocumentLocator (Locator locator)
{
m_Locator = locator;
}
public void startDocument ()
throws SAXException
{
if (m_bOutLog) System.out.println(“startDocument”);
}
public void endDocument ()
throws SAXException
{
if (m_bOutLog) System.out.println(“endDocument”);
}
public void endPrefixMapping (String prefix)
throws SAXException
{
if (m_bOutLog) System.out.println(“endPrefixMapping: “+prefix);
}
public void startElement (String uri, String localName,
String qName, Attributes attributes)
throws SAXException
{
if (m_bOutLog) System.out.println(“startElement: “+uri+“,”+localName+“,”+qName);
}
public void endElement (String uri, String localName, String qName)
throws SAXException
{
if (m_bOutLog) System.out.println(“endElement: “+uri+“,”+localName+“,”+qName);
}
public void characters (char ch[], int start, int length)
throws SAXException
{
if (m_bOutLog) System.out.println(“characters: “+new String(ch, start, length));
}
public void ignorableWhitespace (char ch[], int start, int length)
throws SAXException
{
if (m_bOutLog) System.out.println(“ignorableWhitespace: “+new String(ch, start, length));
}
public void processingInstruction (String target, String data)
throws SAXException
{
if (m_bOutLog) System.out.println(“processingInstruction: “+target+“,”+data);
}
public void skippedEntity (String name)
throws SAXException
{
if (m_bOutLog) System.out.println(“skippedEntity: “+name);
}
////////////////////////////////////////////////////////////////////
// error handlers
////////////////////////////////////////////////////////////////////
public void warning (SAXParseException e)
throws SAXException
{
if (m_bOutLog) System.out.println(“warning: “+e.getMessage());
}
public void error (SAXParseException e)
throws SAXException
{
if (m_bOutLog) System.out.println(“error: “+e.getMessage());
String sAddErrorString = “[XMLChecker2.error] SAXParseException thrown:\n“ + e.getMessage();
m_sErrorString = m_sErrorString + “\n“ + sAddErrorString;
}
public void fatalError (SAXParseException e)
throws SAXException
{
if (m_bOutLog) System.out.println(“fatal error: “+e.getMessage());
String sAddErrorString = “[XMLChecker2.fatalError] SAXParseException thrown:\n“ + e.getMessage();
m_sErrorString = m_sErrorString + “\n“ + sAddErrorString;
throw e;
}
////////////////////////////////////////////////////////////////////
public boolean parseXML(Reader xmlReader, Reader xsdReader)
throws IOException, SAXException, ParserConfigurationException
{
boolean bRes = false;
m_sErrorString = “”;
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
SAXParser parser = saxFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
reader.setErrorHandler(this);
if (xsdReader != null)
{
reader.setProperty(
“http://java.sun.com/xml/jaxp/properties/schemaLanguage",
“http://www.w3.org/2001/XMLSchema");
reader.setProperty(
“http://java.sun.com/xml/jaxp/properties/schemaSource",
new InputSource(xsdReader));
reader.setFeature(“http://xml.org/sax/features/validation", true);
}
try
{
reader.parse(new InputSource(xmlReader));
}
catch (Exception e)
{
if (m_bOutLog) System.out.println(“parse failed: “+e.getMessage());
if (m_sErrorString.length() <= 0) m_sErrorString = e.getMessage();
}
bRes = (m_sErrorString.length() == 0);
return bRes;
}
public static String checkXML(String XmlText, String SchemaFileName)
throws ClassNotFoundException, IOException, SAXException
{
VXMLChecker checker = new VXMLChecker();
Reader xmlReader = null;
Reader xsdReader = null;
try
{
xmlReader = new StringReader(XmlText);
xsdReader = new FileReader(SchemaFileName);
checker.parseXML(xmlReader, xsdReader);
}
catch(Exception e)
{
if (xmlReader != null) xmlReader.close();
if (xsdReader != null) xsdReader.close();
return e.getMessage();
}
if (xmlReader != null) xmlReader.close();
if (xsdReader != null) xsdReader.close();
return checker.m_sErrorString;
}
public static String checkFile(String XmlFileName, String SchemaFileName)
throws ClassNotFoundException, IOException, SAXException
{
VXMLChecker checker = new VXMLChecker();
Reader xmlReader = null;
Reader xsdReader = null;
try
{
xmlReader = new FileReader(XmlFileName);
xsdReader = new FileReader(SchemaFileName);
checker.parseXML(xmlReader, xsdReader);
}
catch(Exception e)
{
if (xmlReader != null) xmlReader.close();
if (xsdReader != null) xsdReader.close();
return e.getMessage();
}
if (xmlReader != null) xmlReader.close();
if (xsdReader != null) xsdReader.close();
return checker.m_sErrorString;
}
}
===
Перепечатка материалов блога разрешается с обязательной ссылкой на blog.coolsoftware.ru