Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2004-10-26
3
Medium Priority
?
276 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
Comment
Question by:harish_alwala
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 19

Accepted Solution

by:
ramazanyich earned 375 total points
ID: 12422684
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
ID: 12441799
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
ID: 12441989
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

598 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