反序列化XML。捕获错误?

时间:2018-08-30 22:34:08

标签: c# xml deserialization

我具有以下反序列化功能(代码段),用于将XML转换为Object。但是,我需要捕获错误,并且它似乎在默默地失败。我想知道何时存在XML与对象不匹配的情况。它不会抛出任何错误或异常,只是忽略了该值。 XmlDeserializationEvents e存在,但充满了空值。

   string Str_Response = Utilities.PostToURL(URL, XML_Request);

   TextReader Txt_Reader = new StringReader(Str_Response);

   XmlReaderSettings XML_Settings = new XmlReaderSettings();

   XmlReader Xml_Reader = XmlReader.Create(Txt_Reader, XML_Settings, (string)null);

   var deserializer = new XmlSerializer(typeof(UPS.TrackResponse));

   XmlDeserializationEvents e = new XmlDeserializationEvents();

   UPS.TrackResponse Response = (UPS.TrackResponse)deserializer.Deserialize(Xml_Reader, e);

1 个答案:

答案 0 :(得分:0)

感谢ryzngard,让我知道我需要做的就是向XmlDeserializationEvents中添加事件处理程序,如下所示:

XmlDeserializationEvents e = new XmlDeserializationEvents();

   e.OnUnknownAttribute += On_UnknownAttribute;
   e.OnUnknownElement += On_UnknownElement;
   e.OnUnknownNode += On_UnknownNode;
   e.OnUnreferencedObject += On_UnreferencedObject;

以及相关的处理程序存根:

  public static void On_UnknownAttribute(object sender, XmlAttributeEventArgs e)
  {
  }

  public static void On_UnknownElement(object sender, XmlElementEventArgs e)
  {
  }

  public static void On_UnknownNode(object sender, XmlNodeEventArgs e)
  {
  }

  public static void On_UnreferencedObject(object sender, UnreferencedObjectEventArgs e)
  {
  }

MSDN文档的拼写不是很好,所以我希望这对以后的人有所帮助。