繁体   English   中英

反序列化带有未知子节点的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序列化为类对象,并且如果可能的话,我宁愿坚持使用它,因为其他一切都很好。 节点自定义只是添加到视频中的自定义元数据,几乎所有内容都可能在那里出现(只有字符串,只有名称和值)。 我使用xsd.exe从我的xml生成类对象,该xml为<custom>标记生成了一个唯一的类,仅对legacyID值使用了一个ulong属性。 问题是,可能存在任意数量的值,我不能也不需要考虑所有值(但以后可能需要阅读特定的值)。

是否可以在我的类中设置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);
        }
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM