473,651 Members | 2,485 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Validating XML Against a XSD Schema

hi guys
I need your suggestions / opinion for doing this the right way.

I have a XML and a Schema for the same

What I want is when its validated against the schema, it should give custom errors saying what happened and where......

is it possible to do that ?

for eg. if the Attribute is missing or invalid in the following element <Watch ID="999d999">
then it should say ID attribute invalid for "Watch" Element.

Right now the validation works but the error returning our very vague, I need a way where I can customize the error or at least let the user know where the error is at what element and which attribute.

thanks,
Shailendra Batham
Nov 16 '05 #1
3 1920
What language do you use? Below is the sample code in C++:

Validating an XML Document Against an XML Schema Using C++
To validate an XML document file with an XML Schema definition language (XSD) schema file using C++, you load XML and XSD documents and create a schema cache as in the following example.

#include "stdio.h"

#import <msxml4.dll>
using namespace MSXML2;

int checkParseError (IXMLDOMParseEr rorPtr pError);
void dump_com_error( _com_error &e);
int main(int argc, char* argv[])
{

CoInitialize(NU LL);
try{

IXMLDOMParseErr orPtr pError;

// load the XML file
// ****** you need to use IXMLDOMDocument 2 interface *********
IXMLDOMDocument 2Ptr pXMLDoc;
HRESULT hr = pXMLDoc.CreateI nstance(__uuido f(DOMDocument40 ));
pXMLDoc->async = VARIANT_FALSE;

hr = pXMLDoc->load("books.xm l");

//check on the parser error
if(hr!=VARIANT_ TRUE)
{
return checkParseError (pXMLDoc->parseError);
}

//load the XSD file
IXMLDOMDocument Ptr pXSDDoc;
hr = pXSDDoc.CreateI nstance(__uuido f(DOMDocument40 ));
pXSDDoc->async = VARIANT_FALSE;

hr = pXSDDoc->load("books.xs d");

//check on the parser error
if(hr!=VARIANT_ TRUE)
{
return checkParseError (pXSDDoc->parseError);
}

//create schemacache
IXMLDOMSchemaCo llectionPtr pSchemaCache;
hr = pSchemaCache.Cr eateInstance(__ uuidof(XMLSchem aCache40));
pXMLDoc->schemas = pSchemaCache.Ge tInterfacePtr() ;

//hook it up with XML Document
hr = pSchemaCache->add("urn:books ", pXSDDoc.GetInte rfacePtr());

//call validate
pError = pXMLDoc->validate();

if(pError->errorCode != S_OK)
{
_bstr_t parseError = _bstr_t("Error code: ")+ _bstr_t(pError->errorCode) +_bstr_t("\n") + _bstr_t("Reason : ")+ pError->Getreason();
MessageBox(NULL , (char*)parseErr or, "Parse Error",MB_OK);
return -1;
}
else
MessageBox(NULL ,"Valiation succeeded", "Results",MB_OK );

}
catch(_com_erro r &e)
{
dump_com_error( e);
}
return 0;
}
int checkParseError (IXMLDOMParseEr rorPtr pError)
{
_bstr_t parseError =_bstr_t("At line ")+ _bstr_t(pError->Getline()) + _bstr_t("\n")+ _bstr_t(pError->Getreason()) ;
MessageBox(NULL ,parseError, "Parse Error",MB_OK);
return -1;

}

void dump_com_error( _com_error &e)
{
printf("Error\n ");
printf("\a\tCod e = %08lx\n", e.Error());
printf("\a\tCod e meaning = %s", e.ErrorMessage( ));
_bstr_t bstrSource(e.So urce());
_bstr_t bstrDescription (e.Description( ));
printf("\a\tSou rce = %s\n", (LPCSTR) bstrSource);
printf("\a\tDes cription = %s\n", (LPCSTR) bstrDescription );
}Input file: books.xml

<?xml version="1.0"?>
<x:catalog xmlns:x="urn:bo oks">
<book id="bk101">
<author>Gambard ella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer </genre>
<price>44.95</price>
<publish_date>2 000-10-01</publish_date>
<description> An in-depth look at creating applications with XML.</description>
</book>
</x:catalog>
Input file: books.xsd

<xsd:schema xmlns:xsd="http ://www.w3.org/2001/XMLSchema" targetNamespace ="urn:books" xmlns:b="urn:bo oks">

<xsd:element name="catalog" type="b:Catalog Data"/>
<xsd:complexTyp e name="CatalogDa ta">
<xsd:sequence >
<xsd:element name="book" type="b:bookdat a" minOccurs="0" maxOccurs="unbo unded"/>
</xsd:sequence>
</xsd:complexType >

<xsd:complexTyp e name="bookdata" >
<xsd:sequence >
<xsd:element name="author" type="xsd:strin g"/>
<xsd:element name="title" type="xsd:strin g"/>
<xsd:element name="genre" type="xsd:strin g"/>
<xsd:element name="price" type="xsd:float "/>
<xsd:element name="publish_d ate" type="xsd:date"/>
<xsd:element name="descripti on" type="xsd:strin g"/>
</xsd:sequence>
<xsd:attribut e name="id" type="xsd:strin g"/>
</xsd:complexType >
</xsd:schema>"Sha ilendra Batham" <sh********@sit esystems.com> wrote in message news:OA******** ******@TK2MSFTN GP11.phx.gbl...
hi guys
I need your suggestions / opinion for doing this the right way.

I have a XML and a Schema for the same

What I want is when its validated against the schema, it should give custom errors saying what happened and where......

is it possible to do that ?

for eg. if the Attribute is missing or invalid in the following element <Watch ID="999d999">
then it should say ID attribute invalid for "Watch" Element.

Right now the validation works but the error returning our very vague, I need a way where I can customize the error or at least let the user know where the error is at what element and which attribute.

thanks,
Shailendra Batham
Nov 16 '05 #2
Hi Shailendra,

If you are coding in .Net,

Look at these:

System.Xml.Sche ma

ValidationEvent Handler
ValidationEvent Args

XmlTextReader xmlreader = new XmlTextReader(" test.xml");
XmlValidatingRe ader valid = new XmlValidatingRe ader(xmlreader) ;
valid.Validatio nType = ValidationType. Schema;

Cheers.

"Shailendra Batham" wrote:
hi guys
I need your suggestions / opinion for doing this the right way.

I have a XML and a Schema for the same

What I want is when its validated against the schema, it should give custom errors saying what happened and where......

is it possible to do that ?

for eg. if the Attribute is missing or invalid in the following element <Watch ID="999d999">
then it should say ID attribute invalid for "Watch" Element.

Right now the validation works but the error returning our very vague, I need a way where I can customize the error or at least let the user know where the error is at what element and which attribute.

thanks,
Shailendra Batham

Nov 16 '05 #3
Thanks for the reply guys.

hey chua I am using C# and I am using the ValidationEvent Handler, it works
fine but this is what error it returns

"The 'ID' attribute has an invalid value according to its data type. An
error occurred at , (2, 9)." string

can we do custom errors like what node's attribute had an error.
"Chua Wen Ching" <ch************ @nospam.hotmail .com> wrote in message
news:FA******** *************** ***********@mic rosoft.com...
Hi Shailendra,

If you are coding in .Net,

Look at these:

System.Xml.Sche ma

ValidationEvent Handler
ValidationEvent Args

XmlTextReader xmlreader = new XmlTextReader(" test.xml");
XmlValidatingRe ader valid = new XmlValidatingRe ader(xmlreader) ;
valid.Validatio nType = ValidationType. Schema;

Cheers.

"Shailendra Batham" wrote:
hi guys
I need your suggestions / opinion for doing this the right way.

I have a XML and a Schema for the same

What I want is when its validated against the schema, it should give
custom errors saying what happened and where......

is it possible to do that ?

for eg. if the Attribute is missing or invalid in the following element
<Watch ID="999d999">
then it should say ID attribute invalid for "Watch" Element.

Right now the validation works but the error returning our very vague, I
need a way where I can customize the error or at least let the user know
where the error is at what element and which attribute.

thanks,
Shailendra Batham

Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3621
by: Will | last post by:
I have been having problems validating an XForms document against the XForms schema located at http://www.w3.org/MarkUp/Forms/2002/XForms-Schema.xsd. I have reduced the XForm to its bare bones as follows: <?xml version="1.0" encoding="iso-8859-1"?> <xf:model xmlns:xf="http://www.w3.org/2002/xforms"> <xf:instance xmlns=""/> </xf:model>
6
2415
by: Iain | last post by:
I've got a system which takes an XML file, translates it into an update gram and then loads it into my database with SQLXML3 (all in dot net). But it's fragile. And the SQLXML 3 error reporting is not absolutely wonderful. So what I want to do is to validate it before I upload it. When I try and do this I get MILLIONS of errors (well lots) complaining about elements like ROOT which are part of the
1
4323
by: Christian | last post by:
Hi, I load an Xml-file "customers.xml" into a DataSet (works fine) but then how do I validate it against a schema (e.g. customers.xsd) ? my customers.xml: <?xml version="1.0" encoding="utf-8"?>| <customers xmlns="http://tempuri.org/customers.xsd"> <Customer ID="1000"> <FirstName>Greg</FirstName>
3
6048
by: Shailendra Batham | last post by:
hi guys I need your suggestions / opinion for doing this the right way. I have a XML and a Schema for the same What I want is when its validated against the schema, it should give custom errors saying what happened and where...... is it possible to do that ? for eg. if the Attribute is missing or invalid in the following element <Watch ID="999d999">
7
4237
by: =?Utf-8?B?Q29kZVJhem9y?= | last post by:
I wrote a method to validate and xml file against a schema. If the file does not conform to the schema, it throws an error. It works fine except for one curious thing. If I try to validate an XDocument (containing schema xml) against a schema url, it validates successfully..... Has anyone ever seen this before or know why it does this. Here is the code:
0
8275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8802
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8465
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8579
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7297
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5612
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4283
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1909
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.