2

I currently have a structure as such

[XmlRoot("command")]
public class Command
{
    [XmlArray("itemlist")]
    [XmlArrayItem("item")]
    public List<Item> Items { get; set; }
}

[XmlRoot("item")]
public class Item
{
    [XmlAttribute("itemid")]
    public string ItemID { get; set; }
}

which works great for it's purpose, but given this xml

<command>
    <itemlist totalsize="999">
        <item itemid="1">
        <item itemid="2">
        ...
    </itemlist>
</command>

how do I get totalsize from itemlist when deserializing? The XML is something I receive and is not something i can control.
I'm not looking for GetAttributeValue or similar, but purely using xmlserializer

smok
  • 355
  • 3
  • 16
  • Possible duplicate of [Read XML Attribute using XmlDocument](http://stackoverflow.com/questions/933687/read-xml-attribute-using-xmldocument) – PMerlet Jan 09 '17 at 12:36
  • YOu need to add an attribute to the4 Command class similar to the ItemID attribute in the Item class. – jdweng Jan 09 '17 at 12:38
  • Hint: copy your xml, go to visual studio and select *Edit > Paste Special > Paste XML as classes*. Though names mapping you should don manually – Sergey Berezovskiy Jan 09 '17 at 12:48

1 Answers1

2

You need to split itemlist and item into two classes.

[XmlRoot("command")]
public class Command
{
    [XmlElement("itemlist")]
    public ItemList ItemList { get; set; }
}

public class ItemList
{
    [XmlAttribute("totalsize")]
    public int TotalSize { get; set; }

    [XmlElement("item")]
    public List<Item> Items { get; set; }
}

public class Item
{
    [XmlAttribute("itemid")]
    public string ItemID { get; set; }
}

As an aside, note that an XmlRoot attribute is only relevant on the root element. The one you have on Item is ignored in this instance.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
  • I figured as much, but hoped that I didn't need to make another class just to hold the extra totalsize. – smok Jan 09 '17 at 13:19