Solved

Need help validating XML against XSD schema.

Posted on 2007-03-26
6
430 Views
Last Modified: 2008-01-09
Hi,

XML and XSD newbie here.  I am trying to validate an XML file with an XSD schema but even when I introduce errors on purpose, I still do not get an validation error.  

Below is my XSD code:

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema id="FlatFileGenXMLSchema"
                  targetNamespace="http://tempuri.org/FlatFileGenXMLSchema.xsd"
                  elementFormDefault="qualified"
                  xmlns="http://tempuri.org/FlatFileGenXMLSchema.xsd"
                  xmlns:mstns="http://tempuri.org/FlatFileGenXMLSchema.xsd"
                  xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="DataSources" type="dataSourcesType"></xs:element>
 
  <xs:complexType name="dataSourcesType">
      <xs:sequence>
            <xs:element name="ZipGroup" type="zipGroupType"></xs:element>
      </xs:sequence>
      <xs:attribute name="continueOnError" type="xs:boolean" />
  </xs:complexType>
 
  <xs:complexType name="zipGroupType">
      <xs:sequence>
            <xs:element name="Summary" type="summaryType" />
            <xs:element name="DataSource" type="dataSourceType" />
      </xs:sequence>
      <xs:attribute name="FileName" type="xs:string" use="required" />
    <xs:attribute name="Destination" type="xs:string" use="required" />
    <xs:attribute name="ToZip" type="xs:string" use="required" />
    <xs:attribute name="intHour" type="xs:int" use="required" />
  </xs:complexType>

  etc...

Below is an excerpt of my XML file:

<?xml version='1.0' encoding='utf-8'?>

<DataSources continueOnError="false">

  <ZipGroup FileName="ZipGroup1" Destination="C:\FlatFile" ToZip="true" intHour="lalalal">
      
      <DataSource>
            <FileName>Person.txt</FileName>
            <Destination>C:\FlatFile</Destination>
            <SQLQuery>SELECT  * FROM PERSONS</SQLQuery>
            <ConnectionString>server=.;uid=xx;pwd=xxxxxxx;database=xxxxxx;</ConnectionString>
            <Factory>System.Data.SqlClient</Factory>
            <Encoding>Unicode</Encoding>
            <AppendDateToFileName>true</AppendDateToFileName>
      </DataSource>

Below is my C# code that is suppose to validate my XML file against the XSD schema:

        private void button1_Click(object sender, EventArgs e)
        {
            string xsdFile = @"C:\mySchema.xsd";
            string xmlFile = @"C:\myXML.xml";

            XmlReader vr;

            //validate XML Schema itself
            ValidationEventHandler handler = new ValidationEventHandler(Form1.Handler);
            XmlSchema schema = XmlSchema.Read(File.OpenRead(xsdFile), handler);
            schema.Compile(handler);

            //validate XML against the Schema
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add("http://tempuri.org/FlatFileGenXMLSchema.xsd", xsdFile);
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);

            FileStream fs = new FileStream(xmlFile, FileMode.Open);

            vr = XmlReader.Create(fs, settings);

            while (vr.Read())
            {
                //do nothing
            }

            vr.Close();

            MessageBox.Show("Doc is valid");


Please notice that I set the values of "intHour" to "lalalala" for the <ZipGroup> element.  In my XSD, I have specified that the "intHour" attribute is suppose to contain only integers.


Thanks
0
Comment
Question by:brdrok
  • 3
  • 2
6 Comments
 
LVL 12

Expert Comment

by:ShazbotOK
ID: 18795722
Where's the eventHandler code?  I am assuming you just forgot to paste that in as well...
0
 
LVL 7

Author Comment

by:brdrok
ID: 18796770
The event handlers are there.  I  didn't want to totally clutter up the screen with code.
0
 
LVL 1

Accepted Solution

by:
cool_bike_rider earned 500 total points
ID: 18798196
Here is the function I am using to validate xml against xsd... Same methode but with a different logic

//convert the xml file into a string and pass as a parameter
public string Validate(string strXMLDoc)
            {
                  try
                  {
                        // Declare local objects
                        XmlTextReader         tr   = null;
                        XmlSchemaCollection   xsc  = null;
                        XmlValidatingReader   vr   = null;
            tr  = new XmlTextReader("xsdFile.xsd");
                        xsc = new XmlSchemaCollection();

      xsc.Add(null, tr);
                        vr = new XmlValidatingReader(strXMLDoc,XmlNodeType.Document, null);
                        vr.Schemas.Add(xsc);
                        vr.ValidationType = ValidationType.Schema;
                        vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
                        while(vr.Read());
                        vr.Close();
                        if (ErrorsCount > 0)
                        {
                              throw new Exception(ErrorMessage);
                        }
                        return("XML validation succeeded.\r\n");
                  }
                  catch(Exception error)
                  {
                        return("XML validation failed." + "\r\n" +
                              "Error Message: " + error.Message);
                  }
            }
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 7

Author Comment

by:brdrok
ID: 18799685
Thank you cool_bike,

in the end it turned out that the attributes of my <xs:schema...> elements were a little out of whack.

I simplified it to the following:

<xs:schema id="FlatFileGenXMLSchema" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

and changed the following line of code from:
settings.Schemas.Add("http://tempuri.org/FlatFileGenXMLSchema.xsd", xsdFile);

to
settings.Schemas.Add("", xsdFile);

I don't know how or why it works, but at this point, I am just glad it works =)

By the way Cool Bike Rider, I am curious why you have wrapped your validation logic inside a Try-Catch statement because you already have the following line of code:

 vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

if I understand correctly the event handler will catch all the invalid xml elements.
0
 
LVL 7

Author Comment

by:brdrok
ID: 18799700
nevermind...the

            if (ErrorsCount > 0)
                        {
                              throw new Exception(ErrorMessage);
                        }

lines somehow didn't register in my head.
0
 
LVL 1

Expert Comment

by:cool_bike_rider
ID: 18806060
Following is my event handler... here 'ErrorMessage' and 'ErrorsCount' are static variables.... same I am using inside validation function.

public static void ValidationHandler(object sender, ValidationEventArgs args)
            {
                  
                  ErrorMessage = ErrorMessage + args.Message + "\r\n";
                  ErrorsCount ++;
            }

I just tried a different logic here... Hope you convinced... :)
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

912 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now