gpt4 book ai didi

c# - 同时编写和验证 XML

转载 作者:数据小太阳 更新时间:2023-10-29 02:12:31 26 4
gpt4 key购买 nike

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

除了尝试读取我刚刚写出的文件(使用架构验证器)之外,我能否在写入 XML 时执行 XSD 验证?

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

最佳答案

对于任何感兴趣的人,我都是这样做的:

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

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

关于c# - 同时编写和验证 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13963920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com