How to deserialize an attribute list item in C #

Hi, I have the following Xml for deserialization:

<RootNode>
    <Item
      Name="Bill"
      Age="34"
      Job="Lorry Driver"
      Married="Yes" />
    <Item
      FavouriteColour="Blue"
      Age="12"
    <Item
      Job="Librarian"
       />
    </RootNote>

How can I deserialize an Item element with a list of attribute key value pairs when I don't know the key names or how many attributes will be?

+1
source share
3 answers

You can use an attribute XmlAnyAttributeto indicate that arbitrary attributes will be serialized and deserialized into a XmlAttribute []property or field when used XmlSerializer.

, Dictionary<string, string>, Item RootNode , proxy XmlAttribute[] XmlAttribute :

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; }
}

fiddle.

0

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...
    }
}

, , 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()
            };
0

Source: https://habr.com/ru/post/1625497/


All Articles