62,041
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
public class Sample
{
public static void Main ()
{
//Load the schema collection.
XmlSchemaCollection xsc = new XmlSchemaCollection();
xsc.Add( "urn:bookstore-schema ", "books.xsd ");
//Validate the file using the schema stored in the collection.
//Any elements belonging to the namespace "urn:cd-schema " generate
//a warning since the there is no schema matching that namespace.
Validate( "store.xml ", xsc);
}
private static void Validate(String filename, XmlSchemaCollection xsc)
{
Console.WriteLine();
Console.WriteLine( "\r\nValidating XML file {0}... ", filename.ToString());
XmlTextReader reader = new XmlTextReader (filename);
XmlValidatingReader vreader=new XmlValidatingReader (reader);
vreader.ValidationType = ValidationType.Schema;
vreader.Schemas.Add(xsc);
//Set the validation event handler.
vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
//Read the XML data.
while (vreader.Read()){}
//Close the reader.
vreader.Close();
}
//Display any warnings or errors.
public static void ValidationCallBack (object sender, ValidationEventArgs args)
{
if (args.Severity==XmlSeverityType.Warning)
Console.WriteLine( "\tWarning: Matching schema not found. No validation occurred. " + args.Message);
else
Console.WriteLine( "\tValidation error: " + args.Message);
}
}