Discussions

XML & Web services: Schema Validation

  1. Schema Validation (28 messages)

    How do I do XML Schema validation in Java.
    I do not want to qualify the elements in my XML with a namespace prefix.

    How should my XML and XSD be?

    Thanks,
    Sudhir

    Threaded Messages (28)

  2. Schema Validation[ Go to top ]

    In the root tag of your XML document, put the following:

    <root xsi:noNamespaceSchemaLocation="[path-to-your-XSD]"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    When you create your XML parser, do the following:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        "http://www.w3.org/2001/XMLSchema");
  3. Schema Validation[ Go to top ]

    How do I specify the schema location if the schema will be present in a jar file. Basically, I do not want the schema to be placed in any particular directory.

    For DTDs we could specify its URL in the DOCTYPE tag of the xml doc and pack the dtd in a jar file.

    Is there a similar way to pack the xsd in a jar and refer to that schema as a URL in the schemaLocation.

    Please let me know
  4. Schema Validation[ Go to top ]

    I have never tried this with Schemas, but the following trick works with DTDs: define an EntityResolver that loads your schema data from the classpath, and assign the EntityResolver to your parser using JAXP. The EntityResolver's loading mechanism can replace the parser's loading mechanism with any logic that you like.
  5. Schema Validation[ Go to top ]

    Hi Paul,
    These are my settings:
    myXSD:
    <xs:schema targetNamespace="some url"
    xmlns="some url"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    >

    myXML:
    <root-element xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNameSpaceSchemaLocation="some url/myXSD.xsd"
    >

    and I have an entity resolver to resolve the URL "some url".

    Am getting the exception SAXParseException:cvc - elt.1: Cannot find the declaration of element 'SynchData'

    Please suggest If I'd missed something
  6. Schema Validation[ Go to top ]

    By EntityResolver, I mean a class like this:


    import org.xml.sax.EntityResolver;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

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

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


    For the above logic to work, you must add the EntityResolver to your document builder:


    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        "http://www.w3.org/2001/XMLSchema");
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new SchemaLoader());


    Finally, your XSD file must be in the root of the classpath. Consult the SAX and JAXP documentation for more info on EntityResolver.
  7. Schema Validation[ Go to top ]

    Hi Paul,
    Did the above things as suggested..
    Still getting the error :
    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'configuration'.

    configuration is my root element.

    Searched some forums for this exception. Some had expressed the suspection that
    this could be bug in xerces.

    Thanks,
    Sudhir
  8. Schema Validation[ Go to top ]

    And found that the method resolveEntity is not called. Feel that the exception being thrown before that.
  9. Schema Validation[ Go to top ]

    I have to admit that I have only used the EntityResolver trick for DTD.
  10. Schema Validation[ Go to top ]

    Hi Paul,
    The xsd gets resolved.
    But getting the following error now:
    org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'component'. One of '{"":component}' is expected.

    Looks like, a prefix is expected for the elements in the XML.

    Pasted below my xml and xsds. Please let me know if any correction is required.

    XML:
    <configuration
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://abc.co.in/batch"
    xsi:schemaLocation="http://abc.co.in/batch
                                http://abc.co.in/batch/batch-configuration.xsd "
    >
    <component component-name="name1" default-connection="defaultDB" />

    XSD:
    <xs:schema targetNamespace="http://abc.co.in/batch" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="http://abc.co.in/batch"
    attributeFormDefault="unqualified"
    elementFormDefault="unqualified">
    ...

    Thanks
    Sudhir
  11. Schema Validation[ Go to top ]

    You problem is this: elementFormDefault="unqualified"

    This means that the only elements that will be in your namespace are those explicitly declared in your XSD. Therefore, the root <configuration> take must be in the namespace, but <component> must not be.

    I would suggest you delete this declaration in your schema, and retain attributeFormDefault="unqualified".
  12. Schema Validation[ Go to top ]

    Hi Paul,
    The xsd gets resolved.
    But getting the following error now:
    Thanks
    Sudhir

    Hi Sudhir,
    I am getting error like
    Error Line 5: cvc-elt.1: Cannot find the declaration of element 'OrderName'.

    You said you got the error resloved but I am not able to.
    please find the details:-

    XsltTutorial.java:-

    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import java.io.*;

    // A Simple SAX Application using JAXP with Namespace support
    public class XsltTutorial{
    private SAXParserFactory factory; // Creates parser object
    private SAXParser parser; // Holds a parser object
    private XMLReader xmlReader; // Object that parses the file
    private DefaultHandler handler; // Defines the handler for this parser
    private boolean valid = true;

    // Set schema constants
        static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
        static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
        static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";


    public XsltTutorial() throws SAXException{
    try{
    factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    factory.setFeature("http://xml.org/sax/features/validation", true);
    factory.setFeature("http://apache.org/xml/features/validation/schema",true);
    factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

    if (factory.isValidating()){
    System.out.println("The parser is validating");
    }

    //Create Parser
    parser = factory.newSAXParser();

    // Enable Schemas
    parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
    parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "file://C:/Program Files/Java/jdk1.5.0_01/bin/ct.xsd");

    System.out.println("The parser is validating1");
    //Create XMLReader
    xmlReader = parser.getXMLReader();
    xmlReader.setEntityResolver(new SchemaLoader());


    ContentHandler cHandler = new MyDefaultHandler();
    ErrorHandler eHandler = new MyDefaultHandler();

    xmlReader.setContentHandler(cHandler);
    xmlReader.setErrorHandler(eHandler);

    System.out.println("The parser is validating2");

    } catch (ParserConfigurationException e){
    e.printStackTrace();
    } catch (SAXException e){
    e.printStackTrace();
    }
    }

    public void parseDocument(String xmlFile){
    try{
    xmlReader.parse(xmlFile);
    if (valid) {
    System.out.println("Document is valid!");
    }
    } catch (SAXException e){
    e.printStackTrace();
    } catch (IOException e){
    e.printStackTrace();
    } catch (Exception e){
    e.printStackTrace();
    }
    }

    public static void main(String[] args){
            try {
                if (args.length != 1) {
                    System.out.println(
                        "Usage: java SimpleSchema " +
                        "[XML Document Filename]");
                    System.exit(0);
                }
    XsltTutorial xmlApp = new XsltTutorial();
    xmlApp.parseDocument(args[0]);
            } catch (SAXException e){
    e.printStackTrace();
    } catch (Exception e) {
                e.printStackTrace();
            }
    }

    class MyDefaultHandler extends DefaultHandler{
    private CharArrayWriter buff = new CharArrayWriter();
    private String errMessage = "";
    /* With a handler class, just override the methods you need to use
    */

    // Start Error Handler code here
    public void warning(SAXParseException e) {
    System.out.println("Warning Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
    }

    public void error(SAXParseException e) {
    errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
    System.out.println(errMessage);
    valid = false;
    }

    public void fatalError(SAXParseException e) {
    errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
    System.out.println(errMessage);
    valid = false;
    }
    }
    }



    SchemaLoader.java:-
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import java.io.*;

    public class SchemaLoader implements EntityResolver {

    public static final String FILE_SCHEME = "file://";

    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
    if(systemId.startsWith(FILE_SCHEME)) {

    String filename = systemId.substring(FILE_SCHEME.length());
    InputStream stream = SchemaLoader.class.getClassLoader().getResourceAsStream(filename);
    return new InputSource(stream);
    } else {
    return null;
    }
    }
    }

    Please let me know the suggestions for the same.
  13. Schema Validation[ Go to top ]

    I was getting simlar errors until I changed my URL from file:// to file///

    I have an entry about it in my blog

    http://khylo.blogspot.com/2005/08/more-xml-schema-validation.html
  14. Schema Validation[ Go to top ]

    I have to admit that I have only used the EntityResolver trick for DTD.
    This trick helped me for to validate against a schema with Xerces2-J. Thank you very much.
    As it may help others too, here is the code:

    ---------
    The code to parse (it uses dom4j, but the same can be done using plain SAX):
    // turn validation on
    org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(true);
    // set the validation feature to true to report validation errors
    reader.setFeature("http://xml.org/sax/features/validation",true);
    // set the validation/schema feature to true to report validation errors against a schema
    reader.setFeature("http://apache.org/xml/features/validation/schema", true);
    // set the validation/schema-full-checking feature to true to enable full schema, grammar-constraint checking
    reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    // set the schema
    reader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "file://config/schema/commons.xsd");
    // set the entity resolver (to load the schema with getResourceAsStream)
    reader.setEntityResolver(new SchemaLoader());

    InputStream stream = XMLUtils.class.getClassLoader().getResourceAsStream(filename);
    if(stream == null) {
    throw new FileNotFoundException("File " + filename + " not found.");
    }
    org.dom4j.Document document = reader.read(stream);
    ---------
    The Entity Resolver (class SchemaLoader):
    public class SchemaLoader implements EntityResolver {

    public static final String FILE_SCHEME = "file://";

    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
    if(systemId.startsWith(FILE_SCHEME)) {
    String filename = systemId.substring(FILE_SCHEME.length());
    InputStream stream = SchemaLoader.class.getClassLoader().getResourceAsStream(filename);
    return new InputSource(stream);
    } else {
    return null;
    }
    }
    }
    ---------
    The xml file (saved under WEB-INF/classes/config/xml/commons.xml):
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <commons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file://config/schema/commons.xsd">
    <remoteUrl>http://www.confidential.com>
    <requestsEnabled>false</requestsEnabled>
    <getDatasource>getDSName</getDatasource>
    <sendDatasource>sendDSName</sendDatasource>
    <updateDatasource>updateDSName</updateDatasource>
    <testDatasourceEnabled>true</testDatasourceEnabled>
    <testDatasource>getDSName</testDatasource>
    <proxyServer>confidential</proxyServer>
    <proxyPort>8080</proxyPort>
    </commons>
    ---------
    The schema file (saved under WEB-INF/classes/config/schema/commons.xsd):
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="commons">
    <xs:annotation>
    <xs:documentation>The root element</xs:documentation>
    </xs:annotation>
    <xs:complexType>
    <xs:sequence>
    <xs:element name="remoteUrl" type="xs:string">
    <xs:annotation>
    <xs:documentation>Url location to exchange data with</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="requestsEnabled" type="xs:boolean">
    <xs:annotation>
    <xs:documentation>Indicates if the servlet can respond to requests</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="getDatasource" type="xs:string">
    <xs:annotation>
    <xs:documentation>JNDI name of the datasource to get data from for get jobs</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="sendDatasource" type="xs:string">
    <xs:annotation>
    <xs:documentation>JNDI name of the datasource to get data from for send jobs</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="updateDatasource" type="xs:string">
    <xs:annotation>
    <xs:documentation>JNDI name of the datasource to get data from for update jobs</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="testDatasourceEnabled" type="xs:boolean">
    <xs:annotation>
    <xs:documentation> Indicates if the datasource is tested with regular http requests</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="testDatasource" type="xs:string">
    <xs:annotation>
    <xs:documentation>Datasource to test on regular http requests to the servlet</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="proxyServer" type="xs:string">
    <xs:annotation>
    <xs:documentation>Proxy server address</xs:documentation>
    </xs:annotation>
    </xs:element>
    <xs:element name="proxyPort" type="xs:unsignedInt" default="0">
    <xs:annotation>
    <xs:documentation>Port for the proxy server</xs:documentation>
    </xs:annotation>
    </xs:element>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:schema>
  15. Schema Validation[ Go to top ]

    Hi, I'm validating my XML files with XSD using dom4j. I just tried Jean-Pol's code, but I'm still getting this error. Whatever I do, I get this wierd error and I don't know why


    org.xml.sax.SAXNotRecognizedException: Feature: http://apache.org/xml/features/validation/schema

    This exception is thrown when on this line:

    reader.setFeature("http://apache.org/xml/features/validation/schema", true);

    Anyone know why?
  16. Schema Validation[ Go to top ]

    Hi Mr.Paul Strack

    In this what is the value for DTD in "systemId.endsWith(DTD)" to be given?
    I am confused

    Regards
    Binu
    +++++++++++==Th following is your reply+++++++++++++
    Schema Validation
    Posted By: Paul Strack on December 02, 2003 @ 09:53 AM in response to Message #102183 1 replies in this thread
    By EntityResolver, I mean a class like this:


    import org.xml.sax.EntityResolver;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

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

      public InputSource resolveEntity(String publicId,
                                       String systemId)
          throws IOException, SAXException {
        if (systemId.endsWith(DTD)) {
          InputStream is =
              this.getClass().getResourceAsStream(XSD);
          return new InputSource(is);
        } else {
          return null;
        }
      }
    }
  17. Are you using Xerces-J?[ Go to top ]

    Are you using Xerces-J 2.4.x, 2.5.x, or 2.6.x ?

    If yes, you can solve this issue by using Xerces-J's schema location
    properties.

    The properties are documented here:
    http://xml.apache.org/xerces-j/properties.html

    Property: http://apache.org/xml/properties/schema/external-schemaLocation

    Property: http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation
  18. Urgent Need Help[ Go to top ]

    Hi,

    Can you please mail me what can be the problem?

    My USGAAP schema contains following: -

    <schema attributeFormDefault="unqualified" xmlns:link="http://www.xbrl.org/2003/linkbase" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.xbrl.org/ca/fr/gaap/pfs/ca-gaap-pfs-2004-11-20" elementFormDefault="qualified" xmlns:xbrli="http://www.xbrl.org/2003/instance" xmlns:ca-gaap-pfs="http://www.xbrl.org/ca/fr/gaap/pfs/ca-gaap-pfs-2004-11-20">


    I ran a few of the files through true north validator and received the following error: -

    ERROR (xbrl.core.xml.SchemaValidationError)

    Location file:/C:/Documents%20and%20Settings/kmaler.CAPITALNYC/Desktop/IMS%20XBRL%20Files/XBRL%20output/02/f34dd6bf-2312-442a-bb5c-0dd4c3face1d.xml, line: 46 col: 99
    Error cvc-complex-type.2.4.a: Invalid content was found starting with element 'ca-gaap-pfs:PropertyPlantEquipmentNet'. One of '{"http://www.xbrl.org/2003/instance":item, "http://www.xbrl.org/2003/instance":tuple, "http://www.xbrl.org/2003/instance":context, "http://www.xbrl.org/2003/instance":unit, "http://www.xbrl.org/2003/linkbase":footnoteLink}' is expected.


    Thanks in advance

    Samata
    samata.vyas@gmail.com
  19. Need Help Urgently[ Go to top ]

    I am getting a same typical error message:
    " cvc-elt.1: Cannot find the declaration of element 'document' "

    here <document> is my root element of the XML.

    My Code is as follows :

    XML
    ===

    <?xml version="1.0" encoding="UTF-8"?>
    <?xml-stylesheet href="spl-2a.1.xsl" type="text/xsl"?>
    <document xsi:schemaLocation="urn:hl7-org:v3 PORR_MT050020.xsd" xmlns="urn:hl7-org:v3" xmlns:splx="urn:hl7-org:splx" xmlns:voc="urn:hl7-org:v3/voc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id root="FFDAA99D"/>
    <code code="34391-3"/>
    <effectiveTime/>
    <address/>
    </document>

    XSD
    ===
    <?xml version="1.0" encoding="ASCII"?>
    <xs:schema xmlns:hl7="urn:hl7-org:v3" xmlns="urn:hl7-org:v3" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:hl7-org:v3" elementFormDefault="qualified">
    <xs:include schemaLocation="template-instantiations.xsd"/>
    <xs:include schemaLocation="voc.xsd"/>
    <xs:include schemaLocation="NarrativeBlock.xsd"/>
    <xs:annotation>
    <xs:documentation>
    Generated using schema builder version 1.21q2.
    11/18/2005: Change made to support package-within-package-within-package product configuration. Refer to Release Notes for SPL Schema.html.
    Stylesheets:

    RoseTreeToMIFStaticModel.xsl version: 1.1
    SplitModels.xsl version: 1.1
    AssocInMif.xsl version:1.1
    StaticMifToXsd.xsl version 1.1</xs:documentation>
    </xs:annotation>
    <xs:element name="document" type="PORR_MT050020.Document"/>
    <xs:complexType name="PORR_MT050020.Document">
    <xs:sequence>
    <xs:element name="id" type="II"/>
    <xs:element name="code" type="CE"/>
    <xs:element name="title" type="CDA.Title" minOccurs="0"/>
    <xs:element name="effectiveTime" type="TS"/>
    </xs:sequence>
    </xs:complexType>
    </xs:schema>

    My Class Code
    =============

    public void validateSPL() {
            try {
                String splObjPath = "C://Documents and Settings/dparikh/My Documents/xmLabelingStage/package.xml
               String xsdPath = "C://Documents and Settings/dparikh/My Documents/xmLabelingStage/PORR_MT050020.xsd";
                SAXParserFactory spf = SAXParserFactory.newInstance();
                spf.setNamespaceAware(true);
                spf.setValidating(true);
                spf.setFeature("http://xml.org/sax/features/validation", true);
                spf.setFeature("http://apache.org/xml/features/validation/schema", true);
                spf.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);

                if (spf.isValidating()) {
                    System.out.println("The parser is validating");
                }

                SAXParser sp = spf.newSAXParser();
                sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
    // sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
    // "http://www.example.com/Report.xsd");
                sp.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "file://C:/Documents and Settings/dparikh/My Documents/xmLabelingStage/PORR_MT050020.xsd");

                //sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",xsdPath);
                //sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",vocxsdPath);
                //sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",narativexsdPath);
                //sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",templatexsdPath);
                //DefaultHandler dh = new DefaultHandler();
                //sp.parse(splObjPath, new ErrorPrinter());
                System.out.println("The parser is validating1");

                //Create XMLReader
                xmlReader = sp.getXMLReader();
                xmlReader.setEntityResolver(new SchemaLoader());

                ContentHandler cHandler = new MyDefaultHandler();
                ErrorHandler eHandler = new MyDefaultHandler();

                xmlReader.setContentHandler(cHandler);
                xmlReader.setErrorHandler(eHandler);

                System.out.println("The parser is validating2");
                parseDocument(splObjPath);
            } catch (SAXException se) {
                se.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } catch (DfException dfe) {
                dfe.printStackTrace();
            }

        }

        public void parseDocument(String xmlFile) {
            try {
                xmlReader.parse(xmlFile);
                if (valid) {
                    System.out.println("Document is valid!");
                }
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        class MyDefaultHandler extends DefaultHandler {
            private CharArrayWriter buff = new CharArrayWriter();
            private String errMessage = "";
    /* With a handler class, just override the methods you need to use
    */

    // Start Error Handler code here
            public void warning(SAXParseException e) {
                System.out.println("Warning Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
            }

            public void error(SAXParseException e) {
                errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
                System.out.println(errMessage);
                valid = false;
            }

            public void fatalError(SAXParseException e) {
                errMessage = new String("Error Line " + e.getLineNumber() + ": " + e.getMessage() + "\n");
                System.out.println(errMessage);
                valid = false;
            }
        }

        public class SchemaLoader implements EntityResolver {

        public static final String FILE_SCHEME = "file://";

        public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
            if (systemId.startsWith(FILE_SCHEME)) {

                String filename = systemId.substring(FILE_SCHEME.length());
                InputStream stream = SchemaLoader.class.getClassLoader().getResourceAsStream(filename);
                return new InputSource(stream);
            } else {
                return null;
            }
        }


    thanks
  20. Schema Validation[ Go to top ]

    Sudhir,

    I have exact same issue.
    I was wondering if you resolved your issue or not.
    Please let me know
    -harsh
  21. Schema Validation[ Go to top ]

    I can only speak for Xerces-J 2.6.2 since that's what I'm using, but you can nuke the resolveEntity() and add:

    db.setNamespaceAware(true);
  22. Schema Validation[ Go to top ]

    Forgot to add this. I do XML fragment validation so I don't have a schema def in the XML. Add this just after the schemaLanguage def.

    db.setAttribute(
      "http://java.sun.com/xml/jaxp/properties/schemaSource",
      new File("/up.xsd"));
  23. i am using Xerces-J 2.6.2.
    My Q is,
    1)do I have to have xsi:schemaLocation="http://www.xyz.com file://c:/dir1/schema1.xsd" in the XML Instance document, in order to validate with SAX or DOM? Or just programmatically specifying in XMLReader.setFeature(...)
  24. i am using Xerces-J 2.6.2.My Q is, 1)do I have to have xsi:schemaLocation="http://www.xyz.com file://c:/dir1/schema1.xsd" in the XML Instance document, in order to validate with SAX or DOM? Or just programmatically specifying in XMLReader.setFeature(...)
    Yes, you have to specify both programmaticaly and in the xml document. If not, you get an error when parsing the file ("Error on line 2 of document : cvc-elt.1: Cannot find the declaration of element 'commons'.", where 'commons' is the root element of your xml file).
    Note : I'm using Xerces-J 2.6.2 too.
  25. i am using Xerces-J 2.6.2.My Q is, 1)do I have to have xsi:schemaLocation="http://www.xyz.com file://c:/dir1/schema1.xsd" in the XML Instance document, in order to validate with SAX or DOM? Or just programmatically specifying in XMLReader.setFeature(...)
    Yes, you have to specify both programmaticaly and in the xml document. If not, you get an error when parsing the file ("Error on line 2 of document : cvc-elt.1: Cannot find the declaration of element 'commons'.", where 'commons' is the root element of your xml file).Note : I'm using Xerces-J 2.6.2 too.
    Doing some more tests, I have even noticed it doesn't use the property from the code: it takes the declaration from the xml file.
    The line reader.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", "file://config/schema/commons.xsd") can be removed.
  26. Needed some inforamation[ Go to top ]

    I am trying to do XML Fragment validation using the xerces API .
    I just saw your post. Can you give me some details as to how to get PSVI for an XML Fragment(i.e. part of the xml document instance) using xerces API.
  27. Needed some inforamation[ Go to top ]

    Jeff .it wud be great if you can reply me back at
    roshan@soncisoftware.com
  28. Dear all:
    i meet a similar problem in XML validation using java, DOM and XML schema.
    As far as i know, there is a bit difference between DOMParser and JAXP. in JAXP we can use as follow:

    factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    .....

    to validate the xml file. but in DOMParser the setValidation() method is protected in the api doc, how can do the validation in DOM?

    can anyone help me?
    thank you very much~~~ :)
  29. used xerces 2.9.0
    Java 1.5
    Mac osx

    <?xml version="1.0"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"   <!-- NO ERROR HERE  AND xmlns:xsd  -->
    targetNamespace="http://www.w3schools.com"  <!-- NO ERROR HERE  AND  must match xsd's xmlns -->
    xmlns="http://www.w3schools.com"
    elementFormDefault="qualified">

    <xsd:element name="order" type="Order" />
        <xsd:complexType name="Order">
            <xsd:all>
                <xsd:element name="user" type="User" minOccurs="1" maxOccurs="1" />
                <xsd:element name="products" type="Products" minOccurs="1" maxOccurs="1" />
            </xsd:all>
        </xsd:complexType>


        <xsd:complexType name="User">
            <xsd:all>
            
                <xsd:element name="deliveryAddress" type="xsd:string" />
            
                <xsd:element name="fullname">
                    <xsd:simpleType>
                        <xsd:restriction base="xsd:string">
                            <xsd:maxLength value="30" />
                        </xsd:restriction>
                    </xsd:simpleType>
                </xsd:element>
                
            </xsd:all>
        </xsd:complexType>


        <xsd:complexType name="Products">


            <xsd:sequence>
                <xsd:element name="product" type="Product" minOccurs="1" maxOccurs="unbounded" />
            </xsd:sequence>
        </xsd:complexType>


        <xsd:complexType name="Product">
            <xsd:attribute name="id" type="xsd:long" use="required" />
            <xsd:attribute name="quantity" type="xsd:positiveInteger" use="required" />
        </xsd:complexType>


    </xsd:schema>

    =============================================================
    <?xml version="1.0"?>
    <order  xmlns="http://www.w3schools.com"    <!-- NO ERROR HERE  AND xmlns must match xsd's xmlns -->
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    <!-- NO ERROR HERE -->
    xsi:schemaLocation="http://www.w3schools.com test.xsd">
     <user>
            <fullname>Bob Jones</fullname>
            <deliveryAddress>
                123 This road,
                That town,
                Bobsville
            </deliveryAddress>
        </user>
        <products>
            <product id="12345" quantity="1" />
            <product id="3232" quantity="3" />
        </products>
    </order>


    1)

    org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'order'.

    or must have used factory.setNameSpaceAware(false);

    Change it to factory.setNameSpaceAware(true);

    Cause: Since the root element order's xmlns does not match the xsd; so error comes.


    2)

    The prefix "xsd" for element "xsd:schema" is not bound.

    <xsd:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" .. />
    The xsd does not declare the prefix xsd so it gives this error.
    The xsd defines the namespace xs but not namespace xsd.

    The xs:schemaLocation does not matter what url it points to. It is optional.


    3)
    Check for this : xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'xsi:schemaLocation' is not allowed to appear in element 'order'.


    4)
    org.xml.sax.SAXParseException: src-resolve.4.2: Error resolving component 'Order'. It was detected that 'Order' is in namespace 'http://www.w3schools1.com', but components from this namespace are not referenceable from schema document 'file:///Users/anand/Documents/workspace/StageForTest/test.xsd'. If this is the incorrect namespace, perhaps the prefix of 'Order' needs to be changed. If this is the correct namespace, then an appropriate 'import' tag should be added to 'file:///Users/anand/Documents/workspace/StageForTest/test.xsd'.

    This occurs when the xsd's targetNamespace does not match with xsd's xmlns.


    package validation;

    import java.io.File;

    import javax.xml.transform.stream.StreamSource;
    import javax.xml.validation.Schema;
    import javax.xml.validation.SchemaFactory;
    import javax.xml.validation.Validator;

    import org.xml.sax.SAXException;

    // Referenced classes of package Validation:
    //            MyErrorHandler

    public class Validate {

        public Validate() {
        }

        public static Schema compileSchema(String s)
            throws SAXException {
            SchemaFactory schemafactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
            if(DEBUG)
                System.out.println((new StringBuilder()).append("schema factory instance obtained is ").append(schemafactory).toString());
            return schemafactory.newSchema(new File(s));
        }

        public static void main(String args[]) {
            try {
                if(args.length != 3)
                    printUsage();
                System.out.println("HI");
                Schema schema = compileSchema(args[0]);
                System.out.println("HI1");

                Validator validator = schema.newValidator();
                System.out.println("HI2");

                validator.setErrorHandler(new MyErrorHandler(Integer.parseInt(args[2])));
                System.out.println("HI3");

                validator.validate(new StreamSource(args[1]));
                System.out.println("HI4");

            }
            catch(Exception exception) {
                exception.printStackTrace();
                System.out.println("GET CAUSE:");
                exception.getCause().fillInStackTrace();
            }
        }

        static void printUsage() {
            System.out.println("java -Xms256M -Xmx256M -jar MechXML.jar <schema file> <XML document> <Error count>");
        }

        private static final boolean DEBUG = System.getProperty("debug") != null;

    }

    package validation;

    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;

    public class MyErrorHandler implements ErrorHandler
    {

        public MyErrorHandler(int i)
        {
            error_cnt = 0;
            fatalError_cnt = 0;
            warning_cnt = 0;
            total_cnt = 0;
            max_cnt = i;
        }

        public void error(SAXParseException saxparseexception) throws SAXException
        {
            System.out.println((new StringBuilder()).append("Line No.: ").append(
                    saxparseexception.getLineNumber()).append(", ERROR: ").append(
                    saxparseexception.toString()).toString());
            error_cnt++;
            if (error_cnt + fatalError_cnt + warning_cnt > max_cnt)
                System.exit(1);
        }

        public void fatalError(SAXParseException saxparseexception)
                throws SAXException
        {
            System.out.println((new StringBuilder()).append("Line No.: ").append(
                    saxparseexception.getLineNumber()).append(", FATAL ERROR: ")
                    .append(saxparseexception.toString()).toString());
            fatalError_cnt++;
            if (error_cnt + fatalError_cnt + warning_cnt > max_cnt)
                System.exit(1);
        }

        public void warning(SAXParseException saxparseexception)
                throws SAXException
        {
            System.out.println((new StringBuilder()).append("Line No.: ").append(
                    saxparseexception.getLineNumber()).append(", WARNING: ")
                    .append(saxparseexception.toString()).toString());
            warning_cnt++;
            if (error_cnt + fatalError_cnt + warning_cnt > max_cnt)
                System.exit(1);
        }

        int error_cnt;
        int fatalError_cnt;
        int warning_cnt;
        int total_cnt;
        int max_cnt;
    }