1

I have an XML string like this:

<foo>
  ...
  <barlist id="10">
    <bar ... />
    <bar ... />
    etc..
  </barlist>
</foo>

How do I get the id of barlist in deserializing it to an object?

My current code for doing this without serializing/deserializing the ID is this:

class FooData{
  [XmlArray("barlist")]
  [XmlArrayItem("bar",typeof(BarData))]
  public List<BarData> Bars;
}
Earlz
  • 62,085
  • 98
  • 303
  • 499
  • Can't be done. XML Serialization treats collections as pure collections - it ignores attributes. – John Saunders May 31 '11 at 15:42
  • possible duplicate of [XmlSerialize a custom collection with an Attribute](http://stackoverflow.com/questions/377486/xmlserialize-a-custom-collection-with-an-attribute) – John Saunders May 31 '11 at 15:47

1 Answers1

2

Try add XmlAtribute to id object.

UPDATE: I'am adding example how you can deserialize it...

Classes:

[XmlType(AnonymousType=true)]
[XmlRoot(Namespace="", IsNullable=false)]
public class foo {
    [XmlElement("barlist")]
    public List<fooBarlist> barlist { get; set; }
}

[XmlType(AnonymousType=true)]
public class fooBarlist {
    [XmlElement("bar")]
    public List<fooBarlistBar> bar { get; set; }
    [XmlAttribute()]
    public byte id { get; set; }
}

[XmlType(AnonymousType=true)]
public class fooBarlistBar {
    [XmlAttribute()]
    public byte number { get; set; }
    [XmlAttribute()]
    public string value { get; set; }
}

test xml:

<foo>
 <barlist id="1">
  <bar number="1" value="Hi" />
  <bar number="2" value="Hello" />
  </barlist>
  <barlist id="2">
  <bar number="3" value="Bye" />
  <bar number="4" value="Bye bye" />
  </barlist>
</foo>

and the code to deserialize xml to object:

XmlSerializer serializer = new XmlSerializer(typeof(foo));
XmlReader reader = XmlReader.Create("D:\\test.xml");
foo testObj = serialier.Deserialize(reader) as foo;

and then we have result

result

Renatas M.
  • 11,694
  • 1
  • 43
  • 62