Thursday, January 29, 2009

Validating XML against XSD in Java

To validate XML documents against XSD in java...

You can use the DocumentBuilderFactory or SAXParserFactory from

        String JAXP_SCHEMA_SOURCE = "";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        String schemaSource = "Path to your XSD";
        Source schemaSourceSrc = new StreamSource(schemaSource);        // has various constructors to pass xsd as a file,url,stream and so on ...
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaSourceSrc);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(" your xml file ");

This will validate your xml file against the xsd. Many examples in the web show similar snippets...  More details are on the link below from sun


Note: If your XSD document contains regular expressions or data type restrictions then they are also validated.


  1. I don have xml file but i have xml data in string, can i use string data instead of providing xml file ?

  2. Sure you can you could use the StringReader to pass it to your inputstream

  3. If I have only the Xpath instead of the whole xml is it possible?

  4. Thanks for very useful should i validate my XMLObject with XSD instead of xml file.