问题描述
当我使用XmlTextReader反序列化XML文档时,没有相应类的文本元素将被忽略.
When I deserialize an XML document with XmlTextReader, a textual element for which there is no corresponding class is simply ignored.
注意:这不是不是关于XML中缺少的元素的元素,该元素必须存在,而是存在于XML文本中,但没有等效项代码中的属性.
Note: this is not about elements missing from the XML, which one requires to be present, but rather being present in the XML text, while not having an equivalent property in code.
我希望得到一个例外,因为如果运行时数据中缺少相应的元素,而我稍后对其进行序列化,则生成的XML文档将与原始文档不同.因此,忽略它是不安全的(在我的实际情况下,我只是忘记定义给定文档包含的99多个类之一,而我起初没有注意到).
I would have expected to get an exception because if the respective element is missing from the runtime data and I serialize it later, the resulting XML document will be different from the original one. So it's not safe to ignore it (in my real-world case I have just forgotten to define one of the 99+ classes the given document contains, and I didn't notice at first).
这是正常现象吗?如果是,为什么?如果元素无法序列化,我可以以某种方式请求获取异常吗?
So is this normal and if yes, why? Can I somehow request that I want to get exceptions if elements cannot be serialized?
在以下示例XML中,我故意拼写错误的"MyComandElement"以说明核心问题:
In the following example-XML I have purposely misspelled "MyComandElement" to illustrate the core problem:
<MyRootElement>
<MyComandElement/>
</MyRootElement>
MyRootElement.cs:
MyRootElement.cs:
public class CommandElement {};
public class MyRootElement
{
public CommandElement MyCommandElement {get; set;}
}
反序列化:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyRootElement));
XmlTextReader xmlReader = new XmlTextReader(@"pgtest.xml");
MyRootElement mbs2 = (MyRootElement)xmlSerializer.Deserialize(xmlReader);
xmlReader.Close();
推荐答案
正如我在进一步研究中偶然发现的那样,这个问题实际上很容易解决,因为...
As I have found out by accident during further research, this problem is actually ridiculously easy to solve because...
... XmlSerializer支持事件!所有要做的就是为缺少的元素定义一个事件处理程序
...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);
}
并使用XmlSerializer注册事件:
and register the event with XmlSerializer:
xmlSerializer.UnknownElement += Serializer_UnknownElement;
在 MSDN ,在那里人们也了解到这一点
The topic is treated at MSDN, where one also learns that
不足为奇的是,还会发生缺少属性,节点和对象的事件.
Not surprisingly, there are also events for missing attributes, nodes and objects.
这篇关于反序列化过程中只会忽略未知元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!