正如您在打击代码中看到的,我想将自定义xml反序列化为对象,我不知道有多少代码属性,所以我想过滤包含“代码”的所有属性,并将其映射到List属性。有没有办法实现这个功能?
<Root>
<FirstElement FirstCode="1" SecondCode="2" ThirdCode="3" Id="1" Name="Element" />
</Root>
public class MappedClass
{
[XmlAttribute(AttributeName = "Name")]
public string Name {get;set;}
[XmlAttribute(AttributeName = "Id")]
public int Id {get;set;}
[?]
public List<Code> Codes {get;set;}
}
public Class Code
{
public string Name {get;set;}
public string Value {get;set;}
}
答案 0 :(得分:1)
我想你可以。使用UnknownAttribute事件将未知属性放入代码集合:
var serializer = new XmlSerializer(typeof(MappedClass));
serializer.UnknownAttribute +=
(s, e) =>
{
(e.ObjectBeingDeserialized as MappedClass).Codes.Add(new Code { Name = e.Attr.Name, Value = e.Attr.Value });
};