1

我有一个 Xml 架构 CustomerData.xsd,我使用 Microsoft 的 xsd.exe 创建类 CustomerData。

我的程序读取一个 Xml 文件,使用 XmlSerializer 使用以下代码获取 CustomerData 的实例:

XmlSerializer serializer = new XmlSerializer(typeof(CustomerData));
TextReader textReader = new StreamReader(fileName);
CustomerData customerData = (CustomerData)serializer.Deserialize(textReader);
textReader.Close();

当我的程序运行时,可以修改 customerData,并且根据架构,某些值可能无效。

在用户将此数据保存回文件之前,我希望能够对其进行验证。如何在保存前验证数据?

注意 - 我将架构编译为嵌入式资源,因此我可以使用如下代码来访问架构:

Assembly myAssembly = typeof(CustomerData).Assembly;
Stream schemaStream = myAssembly.GetManifestResourceStream(schemaResourceName);

我也知道如何制作一个验证 SchemaReader:

XmlReader schemaReader = XmlReader.Create(schemaStream);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, schemaReader);
settings.ValidationType = ValidationType.Schema;

我只是不知道接下来要做什么。

4

1 回答 1

0

对代码进行最小的更改:

// Get the data that the customer has entered
TextReader textReader = new StreamReader(fileName);

// Create the validating reader
XmlReader schemaReader = XmlReader.Create(schemaStream);
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, schemaReader);
settings.ValidationType = ValidationType.Schema;
var documentReader = XmlReader.Create(textReader, settings);

// Use the validating reader to read
try 
{
    while (documentReader.Read())
    {
    }
}
catch (XmlSchemaValidationException ex) 
{
    //do logging or whatever here
}

但是使用 XmlDocument 而不是 XmlReader 的代码要少一些:

 // Get the data that the customer has entered
TextReader textReader = new StreamReader(fileName);

// Create an XmlDocument to read the data
XmlDocument xmlDocument = new XmlDocument();

// Attach the schema to the XmlDocument
xmlDocument.Schemas = new XmlSchemaSet();
xmlDocument.Schemas.Add(null, new XmlTextReader(schemaStream));

// Load the document and validate it
xmlDocument.Load(textReader);
List<String> errors = new List<String>();
xmlDocument.Validate((sender, eventArgs) => errors.Add(eventArgs.Message));
// the errors list will now contain a list of schema errors
于 2013-07-23T22:31:32.423 回答