C# 反序列化具有未知子节点的xml节点
我有一些xml如下所示:C# 反序列化具有未知子节点的xml节点,c#,xml,serialization,C#,Xml,Serialization,我有一些xml如下所示: <?xml version="1.0" encoding="UTF-8"?> <response> <video key="8bJ8OyXI"> <custom> <legacyID>50898311001</legacyID> </custom> <date>1258497567</date>
<?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>
50898311001
1258497567
一些描述
486.20
bc89fde37ef103db26b8a9d98065d006
视频
99416259
文件
准备好的
0
我正在使用XmlSerializer
将xml序列化为类对象,如果可能的话,我更愿意使用它,因为其他一切都可以正常工作。“自定义节点”只是添加到视频中的自定义元数据,几乎所有内容都可能在其中结束(只有字符串,只有名称和值)。我使用xsd.exe从我的xml生成类对象,它为
标记生成了一个唯一的类,只有一个ulong属性用于legacyID值。问题是,可能存在任意数量的值,我不能也不需要解释所有值(但我以后可能需要阅读特定值)
是否可以在我的类中设置Video.Custom属性,以便序列化程序可以将这些值反序列化为类似于
字典的内容?我不需要这些特定值的类型信息,保存节点名+值就足够了。您可以处理UnknowneElement
事件,并将自定义元素反序列化到字典中
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);
}
}
};
serializer.unknowneElement+=(s,e)=>
{
if(e.Element.LocalName==“custom”&&e.ObjectBeingDeserialized是视频)
{
视频=(视频)e.objectbeing反序列化;
如果(video.Custom==null)
{
video.Custom=新字典();
}
foreach(e.element.OfType()中的XmlElement元素)
{
XmlText text=(XmlText)element.FirstChild;
video.Custom.Add(element.LocalName,text.Value);
}
}
};
检查一下:您可以实现IXmlSerializable
接口。@Alexandru这实际上很巧妙,但我希望在这里继续使用XmlSerializer,因为它可以完美地完成我需要的所有其他功能