我有一些看起来像这样的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生成类对象,它为<custom>
标记生成一个唯一的类,只有一个ulong属性用于legacyID值。问题是,可能存在任意数量的值,我不能也不需要考虑它们(但我可能需要稍后读取特定值)。
是否可以在我的类中设置Video.Custom属性,以便序列化程序可以将这些值反序列化为类似Dictionary<string, string>
的内容?我不需要这些特定值的类型信息,保存节点名称+值对于我的目的来说已经足够了。
答案 0 :(得分:1)
您可以处理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);
}
}
};