Validating an XML against referenced XSD in C#(在 C# 中针对引用的 XSD 验证 XML)
问题描述
我有一个带有指定架构位置的 XML 文件,例如:
I have an XML file with a specified schema location such as this:
xsi:schemaLocation="someurl ..localSchemaPath.xsd"
我想在 C# 中进行验证.当我打开文件时,Visual Studio 会根据架构验证它并完美地列出错误.但是,不知何故,如果不指定要验证的架构,我似乎无法在 C# 中自动验证它:
I want to validate in C#. Visual Studio, when I open the file, validates it against the schema and lists errors perfectly. Somehow, though, I can't seem to validate it automatically in C# without specifying the schema to validate against like so:
XmlDocument asset = new XmlDocument();
XmlTextReader schemaReader = new XmlTextReader("relativeSchemaPath");
XmlSchema schema = XmlSchema.Read(schemaReader, SchemaValidationHandler);
asset.Schemas.Add(schema);
asset.Load(filename);
asset.Validate(DocumentValidationHandler);
我不应该能够使用 XML 文件中指定的架构自动进行验证吗?我错过了什么?
Shouldn't I be able to validate with the schema specified in the XML file automatically ? What am I missing ?
推荐答案
您需要创建一个 XmlReaderSettings 实例,并在创建时将其传递给您的 XmlReader.然后可以订阅设置中的ValidationEventHandler
来接收验证错误.您的代码最终将如下所示:
You need to create an XmlReaderSettings instance and pass that to your XmlReader when you create it. Then you can subscribe to the ValidationEventHandler
in the settings to receive validation errors. Your code will end up looking like this:
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class ValidXSD
{
public static void Main()
{
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
// Parse the file.
while (reader.Read()) ;
}
// Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine(" Warning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine(" Validation error: " + args.Message);
}
}
这篇关于在 C# 中针对引用的 XSD 验证 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中针对引用的 XSD 验证 XML


- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01