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 http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/package-summary.html

        String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);

        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);
       
        factory.setSchema(schema);
        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

"http://java.sun.com/developer/technicalArticles/xml/validationxpath/"

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



4 comments:

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

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

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

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

    ReplyDelete