[英]How to deserialize element with list of attributes in C#
Hi I have the following Xml to deserialize:嗨,我有以下 Xml 需要反序列化:
<RootNode>
<Item
Name="Bill"
Age="34"
Job="Lorry Driver"
Married="Yes" />
<Item
FavouriteColour="Blue"
Age="12"
<Item
Job="Librarian"
/>
</RootNote>
How can I deserialize the Item element with a list of attribute key value pairs when I dont know the key names or how many attributes there will be?当我不知道键名或将有多少属性时,如何使用属性键值对列表反序列化 Item 元素?
You can use the XmlAnyAttribute
attribute to specify that arbitrary attributes will be serialized and deserialized into an XmlAttribute []
property or field when using XmlSerializer
. 您可以使用
XmlAnyAttribute
属性指定在使用XmlSerializer
时将任意属性序列化并反序列化为XmlAttribute []
属性或字段。
For instance, if you want to represent your attributes as a Dictionary<string, string>
, you could define your Item
and RootNode
classes as follows, using a proxy XmlAttribute[]
property to convert the dictionary from and to the required XmlAttribute
array: 例如,如果要将属性表示为
Dictionary<string, string>
,则可以使用代理XmlAttribute[]
属性将字典与所需的XmlAttribute
数组相互转换,以如下方式定义Item
和RootNode
类:
public class Item
{
[XmlIgnore]
public Dictionary<string, string> 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<Item> Items { get; set; }
}
Are you deserializing into a list of objects? 您要反序列化为对象列表吗? You can refer to following post, it has worked for me
您可以参考以下帖子,它对我有用
http://www.janholinka.net/Blog/Article/11 http://www.janholinka.net/Blog/Article/11
Using XmlDocument
class you can just select the "Item" nodes and iterate through the attributes: 使用
XmlDocument
类,您只需选择“ Item”节点并遍历属性即可:
string myXml = "<RootNode><Item Name=\"Bill\" Age=\"34\" Job=\"Lorry Driver\" Married=\"Yes\" /><Item FavouriteColour=\"Blue\" Age=\"12\" /><Item Job=\"Librarian\" /></RootNode>"
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...
}
}
Or, if you want an object containing only the Attributes as List of KeyValuePairs, you could use something like: 或者,如果您想要一个仅包含属性作为KeyValuePairs列表的对象,则可以使用类似以下内容的方法:
var items = from XmlNode node in itemNodes
select new
{
Attributes = (from XmlAttribute attr in node.Attributes
select new KeyValuePair<string, string>(attr.Name, attr.Value)).ToList()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.