JAXP+XML validation with schema!


General J2EE: JAXP+XML validation with schema!

  1. JAXP+XML validation with schema! (1 messages)

    Hi all,

    i have written a Servlet that can service some HTTP+XML requests, and in my servlet i want to validate this XML document (using JAXP) with an XSD schema (campagnes.xsd), but i got a "no grammar found error", i have placed my schema everywhere (Web-Inf\lib, with the servlet ...) and got the same error.
    PS : When i test just a simple Class instead of the servlet it works fine

    hope someone can help me ;-)

    my XML document is like that:

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- edited with XMLSPY v2004 rel. 3 U (http://www.xmlspy.com) by Nabil (PSA) -->
    <str:PSAEnvelope xmlns:int="xml.inetpsa.com/commerce/apres-vente/intervention" xmlns:str="xml.inetpsa.com/structure/informatique/normes/PSA" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:cmn="xml.inetpsa.com/structure/informatique/commun" xsi:schemaLocation="xml.inetpsa.com/commerce/apres-vente/intervention
  2. JAXP+XML validation with schema![ Go to top ]

    By default, you XML parser will try to load your schema file from the file system based on its relative location to the XML file. Since your XML file has does not have a location in the file system, there is no way for the parser to resolve its location.

    Happily, there is a solution to this problem. JAXP/SAX allows you to define a custom org.xml.sax.EntityResolver used to load external resources for XML files (such as schemas and DTDs). Here is some logic:

    public class XSDResolver implements EntityResolver {
      private static final String XSD = ".xsd";
      private static final String XSD_DIR = "/xsd/";

      public InputSource resolveEntity(String publicId, String systemId)
          throws IOException {
        if (systemId.endsWith(XSD)) {
          InputStream is = getClass().getResourceAsStream(XSD_DIR + XSD);
          return new InputSource(is);
        } else {
          return null;

    When you load your parse:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new XSDResolver());

    The above example will load the XSD for the classpath in a subdirectory named "/xsd". Therefore, you should put it in WEB-INF/lib/classes/xsd.