473,725 Members | 2,220 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 12 '05 #1
3 6058
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 12 '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 12 '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 12 '05 #4

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

Similar topics

2
3622
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
2427
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
4335
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>
2
2641
by: Joris Janssens | last post by:
I'm trying to write a program for validating XHTML 1.1-documents against the XHTML 1.1 DTD (which is actually the same as validating an XML-file) but I always get a "(404) Not found" error. This is the program itself : ******************************************************************** using System; using System.Xml; using System.Xml.Schema;
1
4244
by: Craig Beuker | last post by:
Hello, I am experimenting with this XmlValidatingReader and have a question about how it is working (or not working as would be the case) The sample documents and code are included at the end of the post. I am using VS.net 2003, .Net 1.1, Win2k Server I have a simple schema and a simple XML document.
3
1922
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">
2
2128
by: srujana | last post by:
Hi I am validating an xml document against schema . when i am passing the xml file location as an input to the parse method String XmlDocumentUrl="E:/books.xml"; parser.parse(XmlDocumentUrl); it is working fine.
7
4242
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:
4
5743
by: agda.karlberg | last post by:
Hello, I need to remove the DTD reference from an xml document, the reason for this is that we want to validate against a schema instead (which we have locally). It takes up to a minute to fetch all documents referred to in the DTD, and as we have no use for them I want to remove the reference. I'm using XmlReaderSettings to pass in the xml document and the schema, but when I loop through the reader it goes and tries to get
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
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
9401
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...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9179
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,...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
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
4519
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...
2
2637
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.