Solved

I get exception while programatically validating xml file against a schema.

Posted on 2004-10-26
245 Views
Last Modified: 2013-11-19
hi,
  I am trying to programatically validate a xml file against a schema. Please find the xml file, xsd file and code I wrote.
xml:
----
<?xml version="1.0" encoding = "UTF-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file://c:/TestSchema.xsd">
      <RequestPlan>
            <PCPID>1212121</PCPID>
            <PCPClientID>343434343</PCPClientID>
            <Name>Harish Kumar</Name>
      </RequestPlan>
      <RequestPlan>
            <PCPID>10128903</PCPID>
            <PCPClientID>59634032</PCPClientID>
            <Name>Raj</Name>
      </RequestPlan>
      <RequestPlan>
            <PCPID>34623412</PCPID>
            <PCPClientID>234235623412</PCPClientID>
            <Name>Mohan</Name>
      </RequestPlan>
</Root>


xsd:
----
<?xml version="1.0" encoding="UTF-8"?>
      <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
            <xs:element name="Root">
                  <xs:complexType>
                        <xs:sequence>
                              <xs:element name="RequestPlan" type="ReqPl" maxOccurs="unbounded"/>
                        </xs:sequence>
                  </xs:complexType>
            </xs:element>
                  <xs:complexType name="ReqPl">
                        <xs:sequence>
                              <xs:element name="PCPID" type="xs:string"/>
                              <xs:element name="PCPClientID" type="xs:string"/>
                              <xs:element name="Name" type="xs:string"/>
                        </xs:sequence>
                  </xs:complexType>
      </xs:schema>
Client code:
-----

package com.axp.irsc;

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.parsers.XMLParser;
import java.io.File;
import org.w3c.dom.Document;
import java.io.*;
import org.apache.axis.utils.XMLUtils;

public class SchemaValidator
{
  public SchemaValidator()
  {
  }

     public void validateSchema(String SchemaUrl, String strXml)
     {

          try
          {
              System.out.println("SchemaUrl" + SchemaUrl);
               //DOMParser domParser = new DOMParser();
               SAXParser domParser = new SAXParser();
               System.out.println("created object");
               String SchemaUrl="C:\\TestSchema.xsd";

               
               domParser.setFeature("http://xml.org/sax/features/validation",true);
               domParser.setFeature("http://apache.org/xml/features/validation/schema",true);
               domParser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);
               domParser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",SchemaUrl);
               
               Validator handler=new Validator();
               domParser.setErrorHandler(handler);  
               domParser.parse("c:\\IRSCData.xml");


               if(handler.validationError==true)
               {
                    handler.saxParseException.printStackTrace();
               }
               else
                    System.out.println("XML Document is valid");
             
               System.out.println("done the parse");

          }
          catch (Exception e)
          {
               e.printStackTrace();
          }
     }
 
     private class Validator extends DefaultHandler    
     {          
          public boolean  validationError = false;    
          public SAXParseException saxParseException=null;
       
          public void error(SAXParseException exception) throws SAXException    
          {
               validationError = true;    
               saxParseException=exception;
          }          
          public void fatalError(SAXParseException exception) throws SAXException          
          {          
               validationError = true;    
               saxParseException=exception;    
          }          
          public void warning(SAXParseException exception) throws SAXException          
          {          
          }    
     }


     public static void main(String str[]) throws Exception
     {
          System.out.println("Validating XML");
          System.out.println("PARSE XML/XSD DOCUMENTS");
          SchemaValidator validator = new SchemaValidator();
          validator.validateSchema();


     }
}


I get following error:
     org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'Name'.
     at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:232)
    at org.apache.xerces.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:173)
    at org.apache.xerces.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:362)

I get no error if I remove the following line from the above code
   domParser.setFeature("http://xml.org/sax/features/validation",true);

Kindly tell me what the above line is doing in the code also the solution.



0
Question by:harish_alwala
    3 Comments
     
    LVL 19

    Accepted Solution

    by:
    domParser.setFeature("http://xml.org/sax/features/validation",true);
    says to Parser to perform validation of XML against provided XSD schema.
    Your schema file is correct. But in  xml file change attribute xsi:noNamespaceSchemaLocation. You root element should be:
    <Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="c:\TestSchema.xsd">
    0
     

    Author Comment

    by:harish_alwala
    thanks for the solution.
    I have one other query on the same. Is it mandatory to write "<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="c:\TestSchema.xsd">" in xml, because I have to generate xml string progrmatically and validate against schema.


    The same code written above is working even if I dont specify "noNamespaceSchemaLocation" in xml file. Is the code really validating against schema even i dont specify the "noNamespaceSchemaLocation" in xml file??
    Please clarify.

    0
     
    LVL 19

    Expert Comment

    by:ramazanyich
    yes it should, because you use explicit call:
         domParser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",SchemaUrl);

    You can check it by putting some mistake in your xml, eg. add non-specified element into your xml.
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Most of the sites are being standardized with W3C Web Standards. W3C provides lot of web standard services to the web. They have the web specification, process and documentation for all the web standards. You can apply HTML, CSS and Accessibility st…
    Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    845 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    5 Experts available now in Live!

    Get 1:1 Help Now