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

时间:2009-11-13 21:20:41

标签: 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);

    ⁞

1 个答案:

答案 0 :(得分: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());

更多详细信息:Validating XML Data with XmlReader