xml data validation with XmlReader is not working

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
<pre>I am trying to validate xml data using the XmlReader. When I test my method it runs without error but does not catch validation errors in the xml data. <br/>The following is the code I am using and sample data I am testing with. I have checked every source I know of but cannot find where the problem is.[/code]
<pre>using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;

namespace XMLValidationProviderClassLibrary
{
public class XMLValidator
{
// Validation Error Count
static int ErrorsCount = 0;

// Validation Error Message
static string ErrorMessage = "";

public static void ValidationHandler(object sender, ValidationEventArgs args)
{
ErrorMessage = ErrorMessage + args.Message + "rn";
ErrorsCount++;
}
public string Validate(string XMLPath, string XSDPath)
{
try
{
XmlReaderSettings objSettings = new XmlReaderSettings();
objSettings.Schemas.Add(null, XmlReader.Create(XSDPath));
objSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
objSettings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
objSettings.IgnoreComments = true;
objSettings.IgnoreWhitespace = true;
using (XmlReader myReader = XmlReader.Create(XMLPath, objSettings))
{
while (myReader.Read());
myReader.Close();
}

// Raise exception, if XML validation fails
if (ErrorsCount > 0)
{
return ErrorMessage;
}
else
{
return "XML validation succeeded.";
}
}
catch (Exception error)
{
// XML Validation errored
string errMsg = error.ToString();
return errMsg + "rn" + ErrorMessage;
}
}

}
}


Data.xml (Notice that the author first name is misspelled as the format should be like the authors last name.
Validtion should catch this I believe.)

<?xml version=1.0?>
<bookstore xmlns="http://example.books.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
<book genre="A"
publicationdate="1981"
ISBN="1-11111-11-0
<title>title 1</title>
<author>
<FirstName>A</FirstName>
<last-name>B</last-name>
</author>
<price>8</price>
</book>
<book genre="B"
publicationdate="1999"
ISBN="0-222-22222-2
<title>title 2</title>
<author>
<first-name>C</first-name>
<last-name>D</last-name>
</author>
<price>11.99</price>
</book>
</bookstore>
[/code]
<br/><hr class="sig Packey Howatt

View the full article
 
Back
Top