在保存到文件之前验证序列化的Xml

时间:2013-07-23 03:50:19

标签: c# validation xsd xmlserializer xmlreader

我有一个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;

我只是不知道下一步该做什么。

1 个答案:

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