5.6.4 DOMパーサを使用する場合のサンプルプログラム
DOMパーサを使用してXML文書を検証する場合のサンプルプログラム,サンプルプログラムの実行方法,および実行結果について説明します。
(1) サンプルプログラム(SampleValidateDOM.java)
DOMパーサを使用する場合のサンプルプログラム(SampleValidateDOM.java)を次に示します。
import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; import java.io.*; public class SampleValidateDOM implements ErrorHandler{ public static final void main(String[] argv){ if (argv.length != 2) { System.out.println( "Usage: java SampleValidateDOM <xml_file> <schema_file>"); System.exit(1); } try{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); dbf.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaSource", argv[1]); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(new SampleValidateDOM()); Document doc = db.parse(argv[0]); System.out.println("Validation OK"); }catch(ParserConfigurationException e){ e.printStackTrace(); }catch(SAXParseException e){ e.printStackTrace(); }catch(SAXException e){ System.out.println("Validation NG: " + e.getMessage()); }catch(IOException e){ e.printStackTrace(); } } public void warning(SAXParseException exception) throws SAXException { System.out.println("**Parsing Warning**\n" + " Line: " + exception.getLineNumber() + "\n" + " URI: " + exception.getSystemId() + "\n" + " Message: " + exception.getMessage()); } public void error(SAXParseException exception) throws SAXException { System.out.println("**Parsing Error**\n" + " Line: " + exception.getLineNumber() + "\n" + " URI: " + exception.getSystemId() + "\n" + " Message: " + exception.getMessage()); throw new SAXException("Error encountered"); } public void fatalError(SAXParseException exception) throws SAXException { System.out.println("**Parsing Fatal Error**\n" + " Line: " + exception.getLineNumber() + "\n" + " URI: " + exception.getSystemId() + "\n" + " Message: " + exception.getMessage()); throw new SAXException("Fatal Error encountered"); } }
(2) サンプルプログラムの実行結果
このサンプルプログラムの実行結果は標準出力に出力されます。標準出力の内容を次に示します。
- 検証対象にpurchaseOrder.xmlを指定した場合
Validation OK
- 検証対象にpurchaseOrder-fail.xmlを指定した場合
**Parsing Error** Line: 33 URI: file:///<サンプルが格納されたフォルダ>/purchaseOrder-fail.xml Message: KECX06063-E cvc-pattern-valid: Value '111144442222999955' is not facet-valid with respect to pattern '\d{16}' for type '#AnonType_creditNumber'. Validation NG: Error encountered