Unknown elements are just ignored during deserialization

前端 未结 2 1271
走了就别回头了
走了就别回头了 2021-01-07 04:19

When I deserialize an XML document with XmlTextReader, a textual element for which there is no corresponding class is simply ignored.

Note: this is

2条回答
  •  孤城傲影
    2021-01-07 05:02

    As I have found out by accident during further research, this problem is actually ridiculously easy to solve because...

    ...XmlSerializer supports events! All one has to do is to define an event handler for missing elements

    void Serializer_UnknownElement(object sender, XmlElementEventArgs e)
    {
        throw new Exception("Unknown element "+e.Element.Name+" found in "
            +e.ObjectBeingDeserialized.ToString()+" in line "
            +e.LineNumber+" at position "+e.LinePosition);
    }
    

    and register the event with XmlSerializer:

    xmlSerializer.UnknownElement += Serializer_UnknownElement;
    

    The topic is treated at MSDN, where one also learns that

    By default, after calling the Deserialize method, the XmlSerializer ignores XML attributes of unknown types.

    Not surprisingly, there are also events for missing attributes, nodes and objects.

提交回复
热议问题