如何使用C#中的属性列表反序列化元素

嗨,我有以下Xml反序列化:

  <Item FavouriteColour="Blue" Age="12"   

当我不知道密钥名称或将有多少属性时,如何使用属性键值对列表反序列化Item元素?

您可以使用XmlAnyAttribute属性指定在使用XmlSerializer时将任意属性序列化并反序列化为XmlAttribute []属性或字段。

例如,如果要将属性表示为Dictionary ,可以按如下方式定义ItemRootNode类,使用代理XmlAttribute[]属性将字典转换为所需的XmlAttribute数组:

 public class Item { [XmlIgnore] public Dictionary Attributes { get; set; } [XmlAnyAttribute] public XmlAttribute[] XmlAttributes { get { if (Attributes == null) return null; var doc = new XmlDocument(); return Attributes.Select(p => { var a = doc.CreateAttribute(p.Key); a.Value = p.Value; return a; }).ToArray(); } set { if (value == null) Attributes = null; else Attributes = value.ToDictionary(a => a.Name, a => a.Value); } } } public class RootNode { [XmlElement("Item")] public List Items { get; set; } } 

原型小提琴 。

您是否反序列化为对象列表? 你可以参考以下post,它对我有用

http://www.janholinka.net/Blog/Article/11

使用XmlDocument类,您只需选择“Item”节点并迭代属性:

 string myXml = "" XmlDocument doc = new XmlDocument(); doc.LoadXml(myXml); XmlNodeList itemNodes = doc.SelectNodes("RootNode/Item"); foreach(XmlNode node in itemNodes) { XmlAttributeCollection attributes = node.Attributes; foreach(XmlAttribute attr in attributes) { // Do something... } } 

或者,如果您想要一个仅包含属性作为KeyValuePairs列表的对象,您可以使用以下内容:

 var items = from XmlNode node in itemNodes select new { Attributes = (from XmlAttribute attr in node.Attributes select new KeyValuePair(attr.Name, attr.Value)).ToList() };