1 16 19 import javax.xml.parsers.SAXParserFactory ; 20 import javax.xml.transform.Transformer ; 21 import javax.xml.transform.TransformerException ; 22 import javax.xml.transform.TransformerFactory ; 23 import javax.xml.transform.sax.SAXSource ; 24 import javax.xml.transform.stream.StreamResult ; 25 import javax.xml.transform.stream.StreamSource ; 26 27 import org.xml.sax.InputSource ; 28 import org.xml.sax.SAXException ; 29 import org.xml.sax.SAXParseException ; 30 import org.xml.sax.XMLReader ; 31 import org.xml.sax.helpers.DefaultHandler ; 32 33 41 public class ValidateXMLInput 42 { 43 44 public static void main(String [] args) 45 throws Exception 46 { 47 ValidateXMLInput v = new ValidateXMLInput(); 48 v.validate(); 49 } 50 51 void validate() 52 throws Exception 53 { 54 TransformerFactory tfactory = TransformerFactory.newInstance(); 57 if(tfactory.getFeature(SAXSource.FEATURE)) 58 { 59 SAXParserFactory pfactory= SAXParserFactory.newInstance(); 61 pfactory.setNamespaceAware(true); pfactory.setValidating(true); 64 XMLReader reader = pfactory.newSAXParser().getXMLReader(); 66 67 Handler handler = new Handler (); 70 reader.setErrorHandler(handler); 71 72 Transformer t = tfactory.newTransformer( 74 new StreamSource ("birds.xsl")); 75 76 SAXSource source = new SAXSource (reader, 78 new InputSource ("birds.xml")); 79 80 try 82 { 83 t.transform(source, new StreamResult ("birds.out")); 84 } 85 catch (TransformerException te) 86 { 87 System.out.println("Not a SAXParseException warning or error: " + te.getMessage()); 90 } 91 92 System.out.println("=====Done====="); 93 } 94 else 95 System.out.println("tfactory does not support SAX features!"); 96 } 97 98 class Handler extends DefaultHandler 100 { 101 public void warning (SAXParseException spe) 102 throws SAXException 103 { 104 System.out.println("SAXParseException warning: " + spe.getMessage()); 105 } 106 107 public void error (SAXParseException spe) 108 throws SAXException 109 { 110 System.out.println("SAXParseException error: " + spe.getMessage()); 111 } 112 } 113 } 114 | Popular Tags |