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
.
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:
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; }
}
Prototype fiddle.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…