validate xml during serialization

痞子三分冷 提交于 2020-01-06 07:13:06

问题


This post https://stackoverflow.com/a/1708614/5333340 gives a solution on how to validate an xml during deserialization. It also says that similar code can be written for serialization, but I was not able to figure it out.

Can someone give a hint?

I want to do the validation during serialization, so that, if the validation fails at some point, the serialization stops immediately.


Based on the linked answer my deserialization code, where validation takes place, looks like this:

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

The class top is the class representing the root element of my xml schema; I created the classes with xsd.exe.

This works perfectly; when the xml does not conform to the schema, I get an XmlSchemaValidationException.


In order to transfer this approach to my curent serialization code (where no validation takes place), which looks like this

public static void Serialize(top t, Stream strm)
{
    using (XmlWriter wr = XmlWriter.Create(strm))
    {
        _topSerializer.Serialize(wr, t);
    }
}

, I would need to put the XmlReader somewhere, since it's the XmlReader that is needed for validation. But where and how? The XmlReader.Create method takes a TextReader or a Stream as input, so I assume I need to have already put something into the stream before the XmlReader can read it. So

using (XmlReader reader = XmlReader.Create(strm, _settings))
{
    using (XmlWriter wr = XmlWriter.Create(strm))
    {
        _topSerializer.Serialize(wr, t);
    }
}

won't validate the generated xml since the stream is still empty when it goes through the XmlReader. The stream will only be filled AFTER the call of _topSerializier.Serialize, so doing the reading after it makes kind of sense. But then, what to put in there?

using (XmlWriter wr = XmlWriter.Create(strm))
{
    _topSerializer.Serialize(wr, t);

    using (XmlReader reader = XmlReader.Create(strm, _settings))
    {
        // what to do here?
    }
}

(This code also does not validate.)

来源:https://stackoverflow.com/questions/53168867/validate-xml-during-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!