KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > QuickValidator


1
2 import com.saxonica.SchemaAwareTransformerFactory;
3 import net.sf.saxon.FeatureKeys;
4 import net.sf.saxon.om.Validation;
5 import org.xml.sax.helpers.DefaultHandler JavaDoc;
6
7 import javax.xml.transform.Transformer JavaDoc;
8 import javax.xml.transform.TransformerException JavaDoc;
9 import javax.xml.transform.TransformerFactory JavaDoc;
10 import javax.xml.transform.sax.SAXResult JavaDoc;
11 import javax.xml.transform.stream.StreamSource JavaDoc;
12 import java.io.File JavaDoc;
13
14 /**
15  * This class performs schema validation of a source document against the
16  * schema specified in its xsi:schemaLocation attribute
17  */

18
19 public class QuickValidator {
20     
21     private QuickValidator() {
22     }
23
24     /**
25      * Usage: java QuickValidator source.xml schema.xsd
26      * @param args
27      * @throws Exception
28      */

29
30     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
31         if (args.length < 1) {
32             System.err.println("No source file supplied");
33         }
34         try {
35             System.setProperty("javax.xml.transform.TransformerFactory",
36                                "com.saxonica.SchemaAwareTransformerFactory");
37             TransformerFactory factory = TransformerFactory.newInstance();
38             factory.setAttribute(FeatureKeys.SCHEMA_VALIDATION, new Integer JavaDoc(Validation.STRICT));
39             factory.setAttribute(FeatureKeys.VALIDATION_WARNINGS, Boolean.TRUE);
40             if (args.length > 1) {
41                 StreamSource JavaDoc schema = new StreamSource JavaDoc(new File JavaDoc(args[1]).toURI().toString());
42                 ((SchemaAwareTransformerFactory)factory).addSchema(schema);
43             }
44             Transformer JavaDoc trans = factory.newTransformer();
45             StreamSource JavaDoc source = new StreamSource JavaDoc(new File JavaDoc(args[0]).toURI().toString());
46             SAXResult JavaDoc sink = new SAXResult JavaDoc(new DefaultHandler JavaDoc());
47             trans.transform(source, sink);
48         } catch (TransformerException JavaDoc err) {
49             System.err.println("Validation failed: " + err.getMessage());
50         }
51     }
52
53 }
54
Popular Tags