How to deserialize element with list of attributes in C#

前端 未结 2 499
悲哀的现实
悲哀的现实 2020-12-12 03:35

Hi I have the following Xml to deserialize:


    

        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 04:21

    Using XmlDocument class you can just select the "Item" nodes and iterate through the attributes:

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

    Or, if you want an object containing only the Attributes as List of KeyValuePairs, you could use something like:

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

提交回复
热议问题