不推荐的XML验证代码问题C#

lw2*_*009 -1 c# xsd

我正在试图弄清楚如何纠正他弃用的xml架构验证代码.

public static bool ValidateXml(string xmlFilename, string schemaFilename)
{
    ?

    //Forward stream reading access to data
    XmlTextReader forwardStream = new XmlTextReader(xmlFilename);

    //deprecated way of checking agaisnt a schema -- update.
    //xmlreader class.
    XmlValidatingReader validation = new XmlValidatingReader(forwardStream);
    validation.ValidationType = ValidationType.Schema;

    //XmlReader validator = new XmlReader.Create(

    XmlSchemaCollection schemas = new XmlSchemaCollection();
    schemas.Add(null, schemaFilename);
    validation.Schemas.Add(schemas);

    ?
Run Code Online (Sandbox Code Playgroud)

ser*_*nko 6

您需要使用XmlReader和XmlReaderSettings而不是已弃用的类.以下是一个例子:

// Create the XmlSchemaSet class.
XmlSchemaSet sc = new XmlSchemaSet();

// Add the schema to the collection.
sc.Add("urn:bookstore-schema", "books.xsd");

// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);

// Create the XmlReader object.
XmlReader reader = XmlReader.Create("booksSchemaFail.xml", settings);

// Parse the file. 
while (reader.Read());
Run Code Online (Sandbox Code Playgroud)

更多详细信息:使用XmlReader验证XML数据