同时编写和验证XML

时间:2012-12-20 01:25:49

标签: c# .net xml xsd

我有一个Write方法,它序列化使用XmlAttributes的对象。这是非常标准的:

private bool WriteXml(DirectoryInfo dir)
{
    var xml = new XmlSerializer(typeof (Composite));
    _filename = Path.Combine(dir.FullName, _composite.Symbol + ".xml");
    using (var xmlFile = File.Create(_filename))
    {
          xml.Serialize(xmlFile, _composite);
    }
    return true;
}

除了尝试读取我刚写完的文件(使用Schema验证器)之外,我可以在编写XML时执行XSD验证吗?

在将内存写入磁盘之前,我可以将内存流弄乱,但在.Net中似乎通常有一种解决大多数问题的优雅方法。

1 个答案:

答案 0 :(得分:1)

我对此感兴趣的方式对任何感兴趣的人都是这样的:

public Composite Read(Stream stream)
{
    _errors = null;
    var settings = new XmlReaderSettings();
    using (var fileStream = File.OpenRead(XmlComponentsXsd))
    {
        using (var schemaReader = new XmlTextReader(fileStream))
        {
            settings.Schemas.Add(null, schemaReader);
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationEventHandler += OnValidationEventHandler;
            using (var xmlReader = XmlReader.Create(stream, settings))
            {
                var serialiser = new XmlSerializer(typeof (Composite));
                return (Composite) serialiser.Deserialize(xmlReader);
            }
        }
    }
}

private ValidationEventArgs _errors = null;
private void OnValidationEventHandler(object sender, ValidationEventArgs validationEventArgs)
{
    _errors = validationEventArgs;
}

然后使用内存流代替将XML写入文件,执行以下操作:

private bool WriteXml(DirectoryInfo dir)
{
    var xml = new XmlSerializer(typeof (Composite));
    var filename = Path.Combine(dir.FullName, _composite.Symbol + ".xml");
    // first write it to memory
    var memStream = new MemoryStream();
    xml.Serialize(memStream, _composite);
    memStream.Position = 0;
    Read(memStream);
    if (_errors != null)
    {
        throw new Exception(string.Format("Error writing to {0}. XSD validation failed : {1}", filename, _errors.Message));
    }
    memStream.Position = 0;
    using (var outFile = File.OpenWrite(filename))
    {
        memStream.CopyTo(outFile);
    }
    memStream.Dispose();
    return true;
}

这样,在将任何内容写入磁盘之前,您始终会对模式进行验证。