473,232 Members | 1,546 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,232 software developers and data experts.

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 6017
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(IXMLDOMParseErrorPtr pError);
void dump_com_error(_com_error &e);
int main(int argc, char* argv[])
{

CoInitialize(NULL);
try{

IXMLDOMParseErrorPtr pError;

// load the XML file
// ****** you need to use IXMLDOMDocument2 interface *********
IXMLDOMDocument2Ptr pXMLDoc;
HRESULT hr = pXMLDoc.CreateInstance(__uuidof(DOMDocument40));
pXMLDoc->async = VARIANT_FALSE;

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

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

//load the XSD file
IXMLDOMDocumentPtr pXSDDoc;
hr = pXSDDoc.CreateInstance(__uuidof(DOMDocument40));
pXSDDoc->async = VARIANT_FALSE;

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

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

//create schemacache
IXMLDOMSchemaCollectionPtr pSchemaCache;
hr = pSchemaCache.CreateInstance(__uuidof(XMLSchemaCach e40));
pXMLDoc->schemas = pSchemaCache.GetInterfacePtr();

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

//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*)parseError, "Parse Error",MB_OK);
return -1;
}
else
MessageBox(NULL,"Valiation succeeded", "Results",MB_OK);

}
catch(_com_error &e)
{
dump_com_error(e);
}
return 0;
}
int checkParseError(IXMLDOMParseErrorPtr 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\tCode = %08lx\n", e.Error());
printf("\a\tCode meaning = %s", e.ErrorMessage());
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
printf("\a\tSource = %s\n", (LPCSTR) bstrSource);
printf("\a\tDescription = %s\n", (LPCSTR) bstrDescription);
}Input file: books.xml

<?xml version="1.0"?>
<x:catalog xmlns:x="urn:books">
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-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:books">

<xsd:element name="catalog" type="b:CatalogData"/>
<xsd:complexType name="CatalogData">
<xsd:sequence>
<xsd:element name="book" type="b:bookdata" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>

<xsd:complexType name="bookdata">
<xsd:sequence>
<xsd:element name="author" type="xsd:string"/>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="genre" type="xsd:string"/>
<xsd:element name="price" type="xsd:float"/>
<xsd:element name="publish_date" type="xsd:date"/>
<xsd:element name="description" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>"Shailendra Batham" <sh********@sitesystems.com> wrote in message news:OA**************@TK2MSFTNGP11.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.Schema

ValidationEventHandler
ValidationEventArgs

XmlTextReader xmlreader = new XmlTextReader("test.xml");
XmlValidatingReader valid = new XmlValidatingReader(xmlreader);
valid.ValidationType = 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 ValidationEventHandler, 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**********************************@microsof t.com...
Hi Shailendra,

If you are coding in .Net,

Look at these:

System.Xml.Schema

ValidationEventHandler
ValidationEventArgs

XmlTextReader xmlreader = new XmlTextReader("test.xml");
XmlValidatingReader valid = new XmlValidatingReader(xmlreader);
valid.ValidationType = 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
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...
6
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...
1
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"...
2
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...
1
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...
3
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...
2
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);...
7
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...
4
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...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...

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.