本文https://stackoverflow.com/a/1708614/5333340提供了有关在反序列化期间如何验证xml的解决方案。它还说可以为序列化编写类似的代码,但我无法弄清楚。
有人可以提示吗?
我想在序列化过程中进行验证,因此,如果验证在某个时候失败,则序列化将立即停止。
基于链接的答案,我的反序列化代码(进行验证的地方)如下所示:
private static readonly XmlSerializer _topSerializer = new XmlSerializer(typeof(top));
private static readonly XmlSettings _settings = ...
// same as in the linked post, only without `ValidationEventHandler` set
public static top Deserialize(Stream strm)
{
using (StreamReader input = new StreamReader(strm))
{
using (XmlReader reader = XmlReader.Create(input, _settings))
{
return (top)_topSerializer.Deserialize(reader);
}
}
}
类top
是代表我的xml模式的根元素的类;我用xsd.exe创建了这些类。
这很好用;当xml与架构不符时,我得到一个XmlSchemaValidationException
。
为了将此方法转移到我目前的序列化代码(其中未进行验证),
public static void Serialize(top t, Stream strm)
{
using (XmlWriter wr = XmlWriter.Create(strm))
{
_topSerializer.Serialize(wr, t);
}
}
,我需要将XmlReader
放在某处,因为它是进行验证所需的XmlReader
。但是,在哪里以及如何进行? XmlReader.Create
方法采用TextReader
或Stream
作为输入,因此我假设我需要先将某些内容放入流中,然后XmlReader
才能读取它。所以
using (XmlReader reader = XmlReader.Create(strm, _settings))
{
using (XmlWriter wr = XmlWriter.Create(strm))
{
_topSerializer.Serialize(wr, t);
}
}
将不会验证生成的xml,因为流在经过XmlReader
时仍然为空。流只会在调用_topSerializier.Serialize
之后填充,因此在有意义之后进行读取。但是,那要放什么呢?
using (XmlWriter wr = XmlWriter.Create(strm))
{
_topSerializer.Serialize(wr, t);
using (XmlReader reader = XmlReader.Create(strm, _settings))
{
// what to do here?
}
}
(此代码也无法验证。)