問題描述
我有一個帶有指定架構位置的 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!