同时编写和验证XML [英] Simultaneously writing and validating XML

查看:33
本文介绍了同时编写和验证XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Write方法,该方法可以序列化使用XmlAttributes的对象.像这样很标准:

I have a Write method that serializes objects which use XmlAttributes. It's pretty standard like so:

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验证吗?

Apart from trying to read the file I have just written out (with a Schema validator), can I perform XSD validation WHILE the XML is being written?

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

I can mess around with memory streams before writing it to disk, but it seems in .Net there is usually an elegant way of solving most problems.

推荐答案

对于有兴趣的人,我这样做的方式是这样的

The way I've done it is like this for anyone interested:

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写入文件,而不是将XML写入文件:

Then instead of writing the XML to file, using a memory stream do something like:

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;
}

这样,在将任何内容写入磁盘之前,您始终会根据架构进行验证.

That way you're always validating against the schema before anything is written to disk.

这篇关于同时编写和验证XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆