Jon Skeet [C# MVP] wrote:
Can you produce a short but complete program which demonstrates the
problem?
Not exactly short, but here goes...
1. Create a new console app, and paste in this code:
using System;
using System.Xml;
using System.Xml.Schema;
namespace XmlTest
{
class Program
{
static void Main(string[] args)
{
// Schema and XML file names
string uriOfSchema = @"d:\test\po.xsd";
string xmlToValidate = @"d:\test\po.xml";
// Define XmlReader settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.CheckCharacters = true;
settings.CloseInput = true;
// Try reading schema
try
{
settings.Schemas.Add(null, uriOfSchema);
}
catch (System.Xml.XmlException e)
{
Console.WriteLine("Error in " + e.SourceUri + ": " + e.Message);
return;
/* NOTE: If e.Message starts with ', everything before e.Message is
* strangely removed. */
}
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
try
{
using (XmlReader xmlReader = XmlReader.Create(xmlToValidate, settings))
{
if (xmlReader != null)
{
while (xmlReader.Read());
Console.WriteLine("Validation completed.");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
switch (args.Severity)
{
case XmlSeverityType.Error:
Console.WriteLine("Error: " + args.Message);
break;
case XmlSeverityType.Warning:
Console.WriteLine("Warning: " + args.Message);
break;
}
}
}
}
2. Then make a file called po.xsd and paste in this code:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="a" type="xs:string"/
</xs:schema>
(There is an intentional well-formedness error on line 3.)
3. Put this file in a folder of your choice and correct the variable 'uriOfSchema' in the code. You won't need the XML file to run this test.
Gustaf