Click here to Skip to main content
Click here to Skip to main content

Simple code to validate an XML file against a schema file (XSD)

By , 26 May 2005
 

Introduction

I had a need to validate an XML file against a schema file (XSD) in VB.NET. So I wrote a simple app that could do this validation. While I was at it I decided it might be nice to validate the schema file all by itself. The basic core functions could be reused in your code to validate XML files against a schema, or just validate the schema file by itself. So I spent an hour or two to put this SimpleXMLValidator together. Most of the code can be found in partial form in the Visual Studio help files.

Background

I started working on a project where I had the option to use a flat file fixed length format or XML file with a schema. Since there was the need to verify that we didn't lose any data on the transfer of the file to our system, I decided on the XML file with schema (not that I would ever choose a flat file over XML). I figured this would also help catch any changes to the XML format. You know how vendors change their format and don't tell you. Then it is a big guessing game to what changed. This little app helps you identify what is wrong, so you know where to look for, to fix the problem.

The code

There are two functions and one sub that do the real work. Each of the functions calls a delegate (which is the one sub) if a validation error occurs. Note that the signature of the sub is important, (that is, the input variables to the procedure must match the delegate signature). All I am really doing in this sub is setting a variable to mark the file as failed validation and displaying the error in a RichTextBox. Here's the code:

'vb.net
Private Sub ValidationCallBack(ByVal sender As Object, ByVal args As _
    ValidationEventArgs)
        'Display the validation error.  This is only called on error
        m_Success = False 'Validation failed
        writertbox("Validation error: " + args.Message)
End Sub
//C#
private void ValidationCallBack(Object sender, ValidationEventArgs args)
    {
       //Display the validation error.  This is only called on error
       m_Success = false; //Validation failed
       writertbox("Validation error: " + args.Message);
    }

Next we have the XML validation code. Really the only important prerequisite is that the XML file should point to the correct schema file (XSD) inside the XML file on the XSI tag.

Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<ROOTElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="yourschema.xsd">

Here is the code for the XML validation function:

'vb.net
Private Function validatexml(ByVal infile As String) As Boolean
        'First we create the xmltextreader
        Dim xmlr As New XmlTextReader(infile)
        'We pass the xmltextreader into the xmlvalidatingreader
        'This will validate the xml doc with the schema file
        'NOTE the xml file it self points to the schema file
        Dim xmlvread As New XmlValidatingReader(xmlr)

        ' Set the validation event handler
        AddHandler xmlvread.ValidationEventHandler, _
        AddressOf ValidationCallBack
        m_Success = True 'make sure to reset the success var

        ' Read XML data
        While (xmlvread.Read)
        End While
        'Close the reader.
        xmlvread.Close()

        'The validationeventhandler is the only thing that would 
        'set m_Success to false
        Return m_Success
End Function
//C#
private bool validateXml(String infile)
{
    //First we create the xmltextreader
    XmlTextReader xmlr = new XmlTextReader(infile);
    //We pass the xmltextreader into the xmlvalidatingreader
    //This will validate the xml doc with the schema file
    //NOTE the xml file it self points to the schema file
    XmlValidatingReader xmlvread = new XmlValidatingReader(xmlr);

    // Set the validation event handler
    xmlvread.ValidationEventHandler += 
        new ValidationEventHandler (ValidationCallBack);
    m_Success = true; //make sure to reset the success var

    // Read XML data
    while (xmlvread.Read()){}

    //Close the reader.
    xmlvread.Close();

    //The validationeventhandler is the only thing that would set 
    //m_Success to false
    return m_Success;
}

Finally, we have the code to validate the schema (XSD) file directly. As mentioned before, this function has a callback to the same on validation event as the XML validation function did.

Here is the code:

'vb.net
Private Function validateSchema(ByVal infilename As String) As Boolean
        'this function will validate the schema file (xsd)
        Dim sr As StreamReader
        Dim myschema As XmlSchema
        m_Success = True 'make sure to reset the success var
        Try
            sr = New StreamReader(infilename)
            myschema = XmlSchema.Read(sr, AddressOf ValidationCallBack)
            'This compile statement is what ususally catches the errors
            myschema.Compile(AddressOf ValidationCallBack)

        Finally
            sr.Close()
        End Try
        Return m_Success
End Function
//C#
private bool validateSchema(String infilename)
{
    //this function will validate the schema file (xsd)
    XmlSchema myschema; 
    m_Success = true; //make sure to reset the success var
    StreamReader sr = new StreamReader(infilename);
    try
    {
    myschema = XmlSchema.Read(sr, 
        new ValidationEventHandler (ValidationCallBack));
    //This compile statement is what ususally catches the errors
    myschema.Compile(new ValidationEventHandler (ValidationCallBack));
    }                            
        finally
    {
        sr.Close();
    }
    return m_Success;
}

Conclusion

Well, that is it. Not really a lot to it. I am sure many of you already knew how to do this. I kind of wish you had published an article, it would have saved me some time. Still the learning process is always enjoyable and never ends.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

kubben
Web Developer
United States United States
Member
I started my programmer career over 16 years ago doing COBOL and SAS on a MVS mainframe. It didn't take long for me to move into windows programming. I started my windows programming in Delphi (Pascal) with a Microsoft SQL server back end. I started working with vb.net when the beta 2 came out in 2001. After spending most of my programming life as a windows programmer I started to check out asp.net in 2004. I achieved my MCSD.net in April 2005. I have done a lot of MS SQL database stuff. I have a lot of experience with Window Service and Web services as well. I spent three years as a consultant programing in C#. I really enjoyed it and found the switch between vb.net and C# to be mostly syntax. In my current position I am programming in both vb.net and C#. Lately I have been using VS2012 and writing a Windows 8 app. You can search for the app it is called ConvertIT.
 
On a personal note I am a born again Christian, if anyone has any questions about what it means to have a right relationship with God or if you have questions about who Jesus Christ is, send me an e-mail. ben.kubicek[at]netzero[dot]com You need to replace the [at] with @ and [dot] with . for the email to work. My relationship with God gives purpose and meaning to my life.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberraiserle6 Nov '12 - 21:17 
Thx
GeneralValidate XML file Without XSD declarationmemberPiyushVarma9 Dec '10 - 9:14 
I have a need to validate an XML file that does not have XSD file location declared. How can I associate the XSD file in code?
GeneralRe: Validate XML file Without XSD declarationmemberkubben9 Dec '10 - 9:24 
Here is a sample of some simple C# code that works in .net 2.0:
 
private void Form1_Load(object sender, EventArgs e)
{
XmlDocument tmpDoc = new XmlDocument();
tmpDoc.Load(@"Sample.xml");
tmpDoc.Schemas.Add(null, @"Sample.xsd");
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
 
tmpDoc.Validate(eventHandler);
 
}
 
static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
MessageBox.Show("Error: {0}"+ e.Message);
break;
case XmlSeverityType.Warning:
MessageBox.Show("Warning {0}"+ e.Message);
break;
}
 
}
 
Hope that helps.
 
Ben
GeneralRe: Validate XML file Without XSD declarationmemberPiyushVarma9 Dec '10 - 14:47 
Worked like a charm! Thank you very much.
Generalvalidating xml with xsd in 2005 framwork 2.0 [modified]membersvknair15 Nov '10 - 21:10 
Private Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.[Error]
MsgBox("Error: {0}" & Convert.ToString(e.Message))
Exit Select
Case XmlSeverityType.Warning
MsgBox("Warning {0}" & Convert.ToString(e.Message))
Exit Select
Case Else
 
MsgBox("Sucessfully validated")
Exit Select
End Select
 
End Sub
 
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tmpDoc As New XmlDocument()
tmpDoc.Load("D:\xxml\books.xml")
tmpDoc.Schemas.Add(Nothing, "D:\xxml\books.xsd")
Dim eventHandler As New ValidationEventHandler(AddressOf ValidationEventHandler)
 
tmpDoc.Validate(eventHandler)
End Sub
 
i am using the above but i am not getting any msg
i need to get as sucessfully validated & if any error tell the element having the error and the tyep of error as string to int etc...
 
and here the schema (xsd file ) is hardcoded in the code
cant it be that the xml file be specified in the XML file a

modified on Tuesday, November 16, 2010 4:23 AM

GeneralRe: validating xml with xsd in 2005 framwork 2.0memberkubben16 Nov '10 - 1:21 
I am not sure what your issue could be. Have you tried putting a breakpoint in the ValidationEventHandler method? I have used this xml validation many times. Perhaps it is something simple.
 
Ben
GeneralRe: validating xml with xsd in 2005 framwork 2.0membersvknair16 Nov '10 - 1:53 
how do i get a msg if the code is validated sucessfully?
 
i tried but i am not getting that msg
 
secondlay the code uses xsd file name in the code
is it possible to get the name od the xsd file from the xml file & use it?
 
note::
 
how to use the same in vb 6.0
GeneralRe: validating xml with xsd in 2005 framwork 2.0memberkubben16 Nov '10 - 1:59 
So if everything is set up correctly if there is an error in validation you should hit this line of code:
MsgBox("Error: {0}" & Convert.ToString(e.Message))
 
You can change that line of code to do something else. Store the error message some place or whatever you need to do.
 
If the xsd name is in the xml file it should work fine.
 
I guess I would try it first by putting the name in the sample as above.
 
I don't know any way of doing xml validation in vb 6.0. There is probably a way to do it, but this is a .net example.
 
Ben
GeneralRe: validating xml with xsd in 2005 framwork 2.0membersvknair16 Nov '10 - 19:13 
thanks for u r reply
 
if there is a error msg i do i get it
i need to display a message a validated sucessfully with no errors which i am not able to do
secondaly
is tehre any way to get all the error msgs is any all at one instead of one by one error msg
 
if the xsd file name is given in XML file is there a need to add it in the code??
GeneralRe: validating xml with xsd in 2005 framwork 2.0memberkubben17 Nov '10 - 1:36 
You can create some sort a variable. Perhaps and arraylist or a generic array.
Something like private shared errorList as List(of string) = new list(of string)
 
Then replace this line:
MsgBox("Error: {0}" & Convert.ToString(e.Message))
with
errorList.Add(e.Message)
 
Then in the final MsgBox that says your are done you need to loop through your errorList variable.
 
NOTE since this is a shared varible you need to be careful you don't try to validate two xml files at the same time.
 
Hope that helps.
Ben
GeneralRe: validating xml with xsd in 2005 framwork 2.0membersvknair17 Nov '10 - 18:42 
Private Shared errorList As List(Of String) = New List(Of String)
 
Private Shared Sub ValidationEventHandler(ByVal sender As Object, ByVal e As ValidationEventArgs)
Select Case e.Severity
Case XmlSeverityType.[Error]
MsgBox("Error: {0}" & Convert.ToString(e.Message))
'label1.text = "Error: {0}" & Convert.ToString(e.Message)
errorList.Add(e.Message)
 
Exit Select
Case XmlSeverityType.Warning
MsgBox("Warning {0}" & Convert.ToString(e.Message))
Exit Select
Case Else
 
MsgBox("Sucessfully validated")
Exit Select
 

End Select
' Response.write(errorList)
End Sub
 
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tmpDoc As New XmlDocument()
tmpDoc.Load("D:\SAMPLE_XML.xml")
tmpDoc.Schemas.Add(Nothing, "D:\sample.xsd")
Dim eventHandler As New ValidationEventHandler(AddressOf ValidationEventHandler)
 
tmpDoc.Validate(eventHandler)
 
End Sub
 
this is wht i have as per u r latest reply
but i am not able to get the msg if any error or for sucessfully validated
 
======
 
i aslo needed to knw how to generate a xml file using vs2005 wih sql data thr' code
GeneralRe: validating xml with xsd in 2005 framwork 2.0memberkubben18 Nov '10 - 2:09 
In your code after the line tmpDoc.Validate(eventHandler)
You can check the code of errors in your new list variable. If the count is zero then the vaidate worked.
You will want to comment out this line:
MsgBox("Error: {0}" & Convert.ToString(e.Message))
or you will get a message box for each error.
 
I am not sure what you mean by you need to know how to general an xml file using vs2005 with sql data thr code.
I am not sure what you are asking.
 
If you have a .net dataset you can write out an xml file. If you have a sql database there is a for xml clause, but there are a lot of details with that.
 
Ben
GeneralRe: validating xml with xsd in 2005 framwork 2.0membersvknair18 Nov '10 - 19:05 
hi Kubben
thanks done accordingly
 
after
tmpDoc.Validate(eventHandler)
if errolist.count= 0
sucessfully validate
else
displayed the eror msg
 
its working currently
 
2)
i need to create the xml file from sql 2000 database and then do this validation
for creating a xml file i am using
Dim xmlReader As New XmlTextReader(ds.GetXml(), XmlNodeType.Element, Nothing)
Response.ContentType = "text/xml"
Dim xmlWriter As New XmlTextWriter("C:\test.xml", Encoding.UTF8)
xmlWriter.Indentation = 14
xmlWriter.WriteStartDocument()
Dim elementName As String = ""


While xmlReader.Read()

' xmlWriter.WriteStartDocument(True) 'ABC xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ABC.xsd")
 
Select Case xmlReader.NodeType
Case XmlNodeType.Element
xmlWriter.WriteStartElement(xmlReader.Name)
elementName = xmlReader.Name
Exit Select
Case XmlNodeType.Text
xmlWriter.WriteString(xmlReader.Value)
Exit Select
Case XmlNodeType.EndElement

xmlWriter.WriteEndElement()
 

Exit Select
 
End Select
 
with he above code a test.xml is created but its not as per the format needed
the nodes & elements needs to be more structured & looped
how can it be done
 
i need the first line of the xml to be 'ABC xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ABC.xsd")
 
i am not getting it
GeneralRe: validating xml with xsd in 2005 framwork 2.0memberkubben19 Nov '10 - 2:30 
Honestly sql sever 2000 doesn't do xml very well. If you had sql server 2005 or 2008 I think you could do what you wanted. I am not sure if it can be done any easy way in sql server 2000. They added new features that allow you to write out xml in lots of different ways in sql 2005 and above.
 
Sorry I am not going to be much help.
 
Ben
GeneralRe: validating xml with xsd in 2005 framwork 2.0membersvknair2 Dec '10 - 18:33 
Hello Thanks for u r help
i some how managed with teh code
 
the validation code u gave also works fine
just wanted to knw if the validation code can be modified so that the use can get a proper error messgae notify the excat error
 
eg suppose i need to write month as JAN and the user has entered JANAUARY .
it does give teh error msg as string Pattern failed at Janauary
insted can it be given in such he user shld easily understand teh error like the month can have only 3 characters ...........
GeneralRe: validating xml with xsd in 2005 framwork 2.0memberkubben3 Dec '10 - 0:57 
I am glad you were able to get it working.
Unfortunatly, the error message is coming from validating the xml against the schema. The error messages coming from schema validation are often cryptic and not very user frendly. Anyway, if you can determine from the error message what is really wrong you can certainly write some code that checks the error message givin and then change it to something that users would understand.
 
Perhaps there is something else out there, but not that I know of.
 
Ben
GeneralMy vote of 1memberchowdary p18 Oct '10 - 23:24 
not usefull
GeneralMy vote of 1memberddecoy1 Jul '10 - 3:42 
Very Bad
GeneralMy vote of 1memberMuris Hadzimejlic14 Dec '09 - 1:52 
doesn't do what expected
General[My vote of 2] poor articlememberDonsw24 Aug '09 - 6:28 
although you have the source code you have no xml, xsd samples. In trying my own they fail for no given reason. It would be nice to see one that you have that works. also you have no error catching in the application.
 
cheers,
Donsw
My Recent Article : Backup of Data files - Full and Incremental

GeneralRe: [My vote of 2] poor articlememberkubben24 Aug '09 - 6:34 
I would guess that you are using .net 2.0 or above. This article was written a long time ago for .net 1.1. I have a post below that has .net 2.0 code, that I would guess would work better for you.
 
Simple code to validate an XML file against a schema file (XSD)[^]
 
ben
GeneralMy vote of 1memberParesh Gheewala2 Dec '08 - 19:58 
N/A
GeneralXML Validation.memberMember 155719921 May '08 - 23:53 
Hi,
 
Is there any way to find the node that was being validated.
I want to find the complete XPath of the validating node, for traceability.
 
Waiting for your early...Its an urgent pls.
 
Thanks,
Kumar. V
GeneralRe: XML Validation.memberkubben22 May '08 - 1:01 
I don't know any way of doing it. There may be a way. The issue is that the schema validation is just a method call. So you don't really get to step through the process. You just call the method. Normally if you get a schma validation error it should tell you what node, but I am guessing you are looking for something else. Sorry I couldn't be more helpful.
 
Ben
QuestionHow to specify schema namespace for xml file ?memberTejas G. Patel4 Dec '07 - 8:06 
Hi,
I am validating XML file against XSD file.but i m creating xml file at runtime so i m not being able to specify namespace for my xml file which is needed by xml file to be validated by the xsd's schema specification.
I know its like (xmlns) tag.
 
help me ASAP.
 
thanx in advance
AnswerRe: How to specify schema namespace for xml file ?memberkubben12 Jan '08 - 1:50 
Sorry I am just responding now. I didn't get the notification that you posted a question.
 
Anyway, if you are using .net 2.0 there are some posibilities. If you are using .net 1.1 there isn't a great way of doing it.
 
Here is a sample of some simple C# code that works in .net 2.0:
 
private void Form1_Load(object sender, EventArgs e)
{
XmlDocument tmpDoc = new XmlDocument();
tmpDoc.Load(@"Sample.xml");
tmpDoc.Schemas.Add(null, @"Sample.xsd");
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
 
tmpDoc.Validate(eventHandler);
 
}
 
static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
MessageBox.Show("Error: {0}"+ e.Message);
break;
case XmlSeverityType.Warning:
MessageBox.Show("Warning {0}"+ e.Message);
break;
}
 
}
 
You just need to take the code out of the form load method and put it where ever you need it. Also change the hard coded Sample.xml and Sample.xsd to your file names.
 

In your case instead of loading an existing xml doc you can add your dynamic xml to the xml doc.
 
Ben
Generalminoccurs validationmemberRHBKV21 Nov '07 - 18:26 
suppose if i specify minouccurs = 1 for all nodes in xsd and missed (eg:any three nodes continously) in xml input, validating reader showing only one error " The element 'PrimaryHeader' has invalid child element 'EmpName'. Expected 'empID'. An error occurred at , (1, 387).". but it is not showing the errors for remaining 2 elements. Reader skipped to next valid node.
can you help me how to capture all errors like the above error
Thanks
GeneralRe: minoccurs validationmemberkubben22 Nov '07 - 1:26 
I was also frustrated with this functionality, unfortunately I didn't find a way around it. It appears that is just how the validatingreader works. Now perhaps I missed a setting that you can pass in or something. Sorry I don't know how to help you in this case.
 
Ben
GeneralSome .net 2.0 code... [modified]memberkubben22 May '06 - 7:14 
Some people have asked about code that would work in .net 2.0. Here is a sample of some simple C# code that works in .net 2.0:
 
private void Form1_Load(object sender, EventArgs e)
{
XmlDocument tmpDoc = new XmlDocument();
tmpDoc.Load(@"Sample.xml");
tmpDoc.Schemas.Add(null, @"Sample.xsd");
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
 
tmpDoc.Validate(eventHandler);
 
}
 
static void ValidationEventHandler(object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
MessageBox.Show("Error: {0}"+ e.Message);
break;
case XmlSeverityType.Warning:
MessageBox.Show("Warning {0}"+ e.Message);
break;
}
 
}
 
You just need to take the code out of the form load method and put it where ever you need it. Also change the hard coded Sample.xml and Sample.xsd to your file names.
 
Ben
 
-- modified at 14:01 Monday 22nd May, 2006
GeneralDoesn't work for memembervoodoo905521 Mar '07 - 5:16 
I copied the code and nothing happens even when I rename tags and data types. I have never been able to get the xml validation stuff to work.
GeneralRe: Doesn't work for mememberkubben22 Mar '07 - 3:18 
Do you get error messages or something? Hard to figure out the problem without seeing your code or any error messages you are getting.
 
Ben
GeneralApplied XML programming for Microsft .Net by Dino Espositomembereggie528 May '05 - 6:50 
Do you have this book or something?
GeneralRe: Applied XML programming for Microsft .Net by Dino Espositomemberkubben29 May '05 - 16:22 
No actually I don't. I might have to find it to see if what you are saying is true. Like I mentioned in the article, all the source code for this app was more or less gotten from microsoft on-line help from visual studio. I just sort of pulled pieces and parts to make it work like I wanted it to. It is a pretty simple UI, I pretty much just slapped the basic components that I needed.
I will have to stop by Barns and Nobel or something and see what is on page 83 like you suggested in your email.
 
Ben
GeneralSpecifying the schema externallymemberThe Chaos Engine25 May '05 - 21:07 
Hi,
 
How about expanding the artile to show how to specify the schema to validate the XML against at validation time? Rather than relying on a static XSD reference.
 
Thanks
 
Oli
GeneralRe: Specifying the schema externally [modified]memberkubben22 May '06 - 8:13 
Well, this is coming a little late. There are actually better ways of doing this in .net 2.0, Still I had some time so here is the code so the schema doesn't need to be in the xml file:
 
private XmlSchemaCollection _xmlSchemaCollection = new XmlSchemaCollection();
 
private void Form1_Load(object sender, System.EventArgs e)
{
_xmlSchemaCollection.Add("",new XmlTextReader(@"Sample.xsd"));
 
XmlValidatingReader validatingReader = null;
try
{
// Read the file using the validating reader
validatingReader = new XmlValidatingReader(new XmlTextReader(@"Sample.xml"));

validatingReader.ValidationEventHandler +=new ValidationEventHandler(validatingReader_ValidationEventHandler);

validatingReader.Schemas.Add(_xmlSchemaCollection);

while (validatingReader.Read()) {}
}
catch(System.Exception ex)
{
throw new System.Exception("Exception in initial schema validation.",ex);
}
finally
{
validatingReader.Close();
}
}
//Event Handler for validation errors.
private void validatingReader_ValidationEventHandler(object sender, ValidationEventArgs e)
{

switch (e.Severity)
{
case XmlSeverityType.Warning:
MessageBox.Show(e.Message);
break;
case XmlSeverityType.Error:
MessageBox.Show(e.Exception.Message);
break;
}
}
 
I hope it helps. I would guess by now you already have this figured out.
 
Ben
 
-- modified at 14:13 Monday 22nd May, 2006
QuestionRe: Specifying the schema externallymemberthesitemaster9 Mar '07 - 3:44 
To make it possible to pass a string with XSD content instead of a location I changed a single line of the code above:
Original: validatingReader = new XmlValidatingReader(new XmlTextReader(@"Sample.xml"));
New:              
validatingReader = new XmlValidatingReader(new XmlTextReader(new StringReader(xsdInput)));     
     
Besides a warning that this function is qualified as obsolete I get an error: “The targetNamespace parameter '' should be the same value as the targetNamespace 'urn:bookstore-schema' of the schema.”           
 
I’d like to validate a xml string against a xsd string. To make is possible to use this code for every input, I don’t want to use a hard coded target namespace, e.g. urn:bookstore-schema (just like described in post above). How can I retrieve the target namespace out of the XSD string? In stead of manipulating the string, I wonder if it is possible to do this by using the existing API.
 
<code>
string xmlInput
string xsdInput
XmlSchemaSet sc = new XmlSchemaSet();
 
sc.Add(urn:bookstore-schema), XmlReader.Create(new StringReader(xsdInput));
 
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new
ValidationEventHandler(ValidationCallBack);
</code>

AnswerRe: Specifying the schema externallymemberkubben9 Mar '07 - 3:57 
Are you able to use .net 2.0 at all? The xml schema validation stuff is a lot better in .net 2.0. It is a little limited in 1.1.
 
Here is a sample from MS help:
Visual Basic
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports System.IO
 
public class Sample
 
public shared sub Main()
 
' Create the XmlSchemaSet class.
Dim sc as XmlSchemaSet = new XmlSchemaSet()
 
' Add the schema to the collection.
sc.Add("urn:bookstore-schema", "books.xsd")
 
' Set the validation settings.
Dim settings as XmlReaderSettings = new XmlReaderSettings()
settings.ValidationType = ValidationType.Schema
settings.Schemas = sc
AddHandler settings.ValidationEventHandler, AddressOf ValidationCallBack

' Create the XmlReader object.
Dim reader as XmlReader = XmlReader.Create("booksSchemaFail.xml", settings)
 
' Parse the file.
while reader.Read()
end while

end sub
 
' Display any validation errors.
private shared sub ValidationCallBack(sender as object, e as ValidationEventArgs)
Console.WriteLine("Validation Error: {0}", e.Message)
end sub
end class
 

C#
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
 
public class Sample {
 
public static void Main() {
 
// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();
 
// Add the schema to the collection.
sc.Add("urn:bookstore-schema", "books.xsd");
 
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

// Create the XmlReader object.
XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings);
 
// Parse the file.
while (reader.Read());

}
 
// Display any validation errors.
private static void ValidationCallBack(object sender, ValidationEventArgs e) {
Console.WriteLine("Validation Error: {0}", e.Message);
}
}
 

NOTE that when you add the schema to the schema set you can use a xmlreader.
 
So there is a clear way to do it in .net 2.0
 
I supose if you work on it long enough you can figure out a way of doing it in 1.1
 
Hope that helps.
Ben

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 26 May 2005
Article Copyright 2005 by kubben
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid