Hi,
Apologies if this is a really stupid question, I haven't done much xml
before.
I need to validate an xml file against a schema, but when I try to
validate an invalid file it doesn't throw an error.
Here's my C# code:
namespace MyValidationTool
{
class Program
{
static void Main(string[] args)
{
string xmlFileName = "thexmlfile.xml";
string schemaFileName = "theschemafile.xsd";
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
XmlSchemaSet schemas = new XmlSchemaSet();
settings.Schemas = schemas;
schemas.Add(null, schemaFileName);
settings.ValidationEventHandler += new
ValidationEventHandler(settings_ValidationEventHan dler);
XmlReader validator = XmlReader.Create(xmlFileName, settings);
try
{
while (validator.Read())
{
Console.WriteLine("test");
Console.ReadLine();
}
}
catch (XmlException err)
{
Console.WriteLine(err.Message);
Console.ReadLine();
}
finally
{
validator.Close();
}
}
static void settings_ValidationEventHandler(object sender,
ValidationEventArgs e)
{
Console.WriteLine("Validation error: " + e.Message);
Console.ReadLine();
}
}
}
thexmlfile:
<?xml version="1.0" encoding="UTF-8"?>
<note xmlns="http://www.w3schools.com"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="http://www.w3schools.com theschemafile.xsd">
<to>Me</to>
<from>Myself</from>
<heading>Does it work?</heading>
<body>Nope, unfortunately not.</body>
</note>
theschemafile:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://
www.w3schools.com" targetNamespace="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
As I said, if I try to break it by making the xml file invalid it
still doesn't throw an error.
I'm presuming I'm missing something really obvious here, so I'd really
appreciate if anoyone who knows why it's happening could please give
me a pointer in the right direction.
Thanks,
AK