Validating an XML against referenced XSD in C#

后端 未结 5 616
天命终不由人
天命终不由人 2020-11-22 13:33

I have an XML file with a specified schema location such as this:

xsi:schemaLocation=\"someurl ..\\localSchemaPath.xsd\"

I want to validate

5条回答
  •  隐瞒了意图╮
    2020-11-22 14:30

    A simpler way, if you are using .NET 3.5, is to use XDocument and XmlSchemaSet validation.

    XmlSchemaSet schemas = new XmlSchemaSet();
    schemas.Add(schemaNamespace, schemaFileName);
    
    XDocument doc = XDocument.Load(filename);
    string msg = "";
    doc.Validate(schemas, (o, e) => {
        msg += e.Message + Environment.NewLine;
    });
    Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
    

    See the MSDN documentation for more assistance.

提交回复
热议问题