Code example for SAXParser: Parsing XML documents

Methods: getXMLReader, parse, setProperty

0
              if(schemaValidation == true) {
                   //Using JAXP 1.2 to validate an XML document using an external schema. 
	               if (xmlSchema != null) {
	                 spf = SAXParserFactory.newInstance();
	                 parser= spf.newSAXParser();
                    reader = parser.getXMLReader();
 
                    parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
	                 parser.setProperty(JAXP_SCHEMA_SOURCE, xmlSchema);
 
	                 spf.setNamespaceAware(true);
                    spf.setValidating(true);
                   } 
                   //Using JAXP 1.2 to validate an XML document using the xsi:noNamespaceSchemaLocation value. 
                   else { 
                        spf = SAXParserFactory.newInstance();
 
                        spf.setNamespaceAware(true);
                        spf.setValidating(true);
 
                        parser= spf.newSAXParser();
                        reader = parser.getXMLReader();
 
                        parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                    } 
 
	          } 
	          //Validating an XML document using the DOCTYPE value. 
 	          else{ 
                    spf = SAXParserFactory.newInstance();
                    parser= spf.newSAXParser();
                    reader = parser.getXMLReader();
                    //Validate document using DTD. 
                   reader.setFeature("http://xml.org/sax/features/validation", true);
 
	           } 
	          Handler dh = new Handler();
 
              File _anXMLFile = new File(xmlDoc);
              if (_anXMLFile.exists())  parser.parse(_anXMLFile, dh);
            } 
            catch (IOException ioe)  {
                ioe.printStackTrace();
				  setError(true); 
            }