Click to See Complete Forum and Search --> : Validating XML file with local XSD file


DougieDa59
03-10-2010, 06:45 PM
Hey folks,
I'm pretty new to XML so bare with me..

I'm trying to validate an XML file using a XSD file in the same directory. The reference I have in the xml file is:
<?xml version="1.0" encoding="utf-8"?>
<newsandscores xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="C:\news.xsd">

And at the top of the XSD file:
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema targetNamespace="http://tempuri.org/XMLSchema.xsd"
elementFormDefault="qualified"
xmlns="http://tempuri.org/XMLSchema.xsd"
xmlns:mstns="http://tempuri.org/XMLSchema.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"

In the XML file, I have purposely entered a string into an attribute which is defined as an integer in the XSD in the hopes that either Visual Studio or Firefox would show it up as an error but neither do.

Any ideas?
Thanks in advance...

mrkensr
03-17-2010, 01:48 PM
I found this in a book somewhere
Put the full path to your files where it says XMLfileName& XSDFileName

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;


namespace TestReader
{
public class ConsoleValidator
{
private bool failed;

public bool Failed
{
get { return failed; }
}
public bool ValidateXml(string xmlFilename, string schemafilename)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
XmlSchemaSet schemas = new XmlSchemaSet();
settings.Schemas = schemas;
schemas.Add(null, schemafilename);
settings.ValidationEventHandler += ValidationEventHandler;
XmlReader validator = XmlReader.Create(xmlFilename, settings);
failed = false;
try
{
while (validator.Read()) { }
}
catch (XmlException err)
{
Console.WriteLine("Critical XML Error");
Console.WriteLine(err.Message);
failed = true;
}
finally
{
validator.Close();
}
return !failed;
}
private void ValidationEventHandler(object sender, ValidationEventArgs args)
{
failed = true;
Console.WriteLine("Validation error: " + args.Message);
Console.WriteLine();
}

static void Main(string[] args)
{
ConsoleValidator cv = new ConsoleValidator();
Console.WriteLine("Validating XML");
bool success = cv.ValidateXml("D:\\Data\\OutputXml.xml", "D:\\Data\\v5.0.xsd");
if (!success)
Console.WriteLine("Validate Failed");
else
Console.WriteLine("Validate Passed");

Console.ReadLine();
}
}
}