|
I am trying to validate the xml using the schema
which is present locally in the memory. My method looks as follows:
public static void
validateXmlAgainstLocalSchema(String XMLString, String schemaString) throws
SAXException{
long startTime = System.currentTimeMillis(); System.out.println("Files: XML:" + XMLString + " XSD:" + schemaString); XMLReader parser = null; // Instantiate a parser try{ parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); } catch (org.xml.sax.SAXException ex){ System.out.println("SAXException Exception"); throw new SAXException("Error Obtaining the parser."); }
try{
// Register the error
handler
parser.setErrorHandler(new SchemaErrorHandler());
//parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error",
true);
// Turn on validation parser.setFeature("http://xml.org/sax/features/namespaces",true); parser.setFeature("http://xml.org/sax/features/validation", true); parser.setFeature("http://apache.org/xml/features/validation/schema",true); parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true); //parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",Schema); parser.setEntityResolver(new SchemaEntityResolver(schemaString)); } catch (org.xml.sax.SAXNotRecognizedException ex){ ex.printStackTrace(); System.out.println("SAXNotRecognizedException Exception"); } catch (org.xml.sax.SAXNotSupportedException ex){ ex.printStackTrace(); System.out.println("SAXNotSupportedException Exception"); } // Parse
the
document
try{ //String XMLSystemId = new File(XMLString).toURL().toExternalForm(); parser.parse(new InputSource(new StringReader(XMLString))); //parser.parse(XMLSystemId); System.out.println("Parsed Successfully by SAX Parser"); } catch (org.xml.sax.SAXException ex){ System.out.println("SAXException Exception"); throw new SAXException("Error Validating the content XML."); } catch (java.io.IOException ex){ System.out.println("IOException Exception"); throw new SAXException("Error Validating the content XML."); } finally { long endTime = System.currentTimeMillis(); System.out.println("Total time of SAXValidate:"+(endTime-startTime)); } }//SAXValidate And SchemaEntityResolver looks as follows:
public class SchemaEntityResolver implements EntityResolver
{
InputSource source = null; public SchemaEntityResolver(String schemaString) { source = new InputSource(new StringReader(schemaString)); } public InputSource resolveEntity(String publicID, String systemID) throws SAXException { return source; } } When I try to validate an xml with the schema string, I get the following
error:
Line: 1
URI: null Message: cvc-elt.1: Cannot find the declaration of element 'content'. Am I doing it wrong? If so please tell me how to use the
entityresolver.
Praveen
|
