反序列化 xml 具有未知子节点的节点

deserialize xml node with unknown child nodes

我有一些 xml 看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <video key="8bJ8OyXI">
      <custom>
        <legacyID>50898311001</legacyID>
      </custom>
      <date>1258497567</date>
      <description>some description</description>
      <duration>486.20</duration>
      <md5>bc89fde37ef103db26b8a9d98065d006</md5>
      <mediatype>video</mediatype>
      <size>99416259</size>
      <sourcetype>file</sourcetype>
      <status>ready</status>
      <views>0</views>
    </video>
 </response>

我正在使用 XmlSerializer 将 xml 对象序列化为 class 对象,如果可能的话我更愿意坚持使用它,因为其他一切都工作正常。节点自定义只是添加到视频中的自定义元数据,几乎任何东西都可能在那里结束(只有字符串,只有名称和值)。我使用 xsd.exe 从我的 xml 生成了 class 对象,它为 <custom> 标签生成了一个唯一的 class,只有一个 legacyID 值的 ulong 属性。问题是,可能存在任意数量的值,我不能也不需要考虑所有值(但我可能需要稍后阅读特定值)。

是否可以在我的 class 中设置 Video.Custom 属性,以便序列化程序可以将这些值反序列化为 Dictionary<string, string> 之类的东西?我不需要这些特定值的类型信息,保存节点名称 + 值就足够了。

您可以处理 UnknownElement 事件并将 custom 元素反序列化到您的字典中

serializer.UnknownElement += (s, e) =>
{
    if (e.Element.LocalName == "custom" && e.ObjectBeingDeserialized is Video)
    {
        Video video = (Video)e.ObjectBeingDeserialized;

        if (video.Custom == null)
        {
            video.Custom = new Dictionary<string, string>();
        }

        foreach (XmlElement element in e.Element.OfType<XmlElement>())
        {
            XmlText text = (XmlText)element.FirstChild;
            video.Custom.Add(element.LocalName, text.Value);
        }
    }
};