Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 views
in Technique[技术] by (71.8m points)

xml - How to deserialize element with list of attributes in C#

Hi I have the following Xml to deserialize:

<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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...