views:

186

answers:

2

Hopefully a question with a very simple answer, but it's not one that I've been able to find. I have a small XML document that looks roughly like this:

<aa>
  <bb><name>bb1</name></bb>
  <bb><name>bb2</name></bb>
  <bb><name>bb3</name></bb>
</aa>

I have classes that represent aa and bb

[XmlRoot("aa")]
public class aa
{
  [XmlArray("bbs")]
  [XmlArrayItem("bb")]
  public bb[] bbs;
}

public class bb
{
  [XmlElement("name")]
  public string Name;
}

When I try to deserialize the document using an XmlSerializer I get an aa object with a null bbs property. As I understand it this is because the attributes I've used on the bbs property tell the serializer to expect a document like this:

<aa>
  <bbs>
    <bb><name>bb1</name></bb>
    <bb><name>bb2</name></bb>
    <bb><name>bb3</name></bb>
  </bbs>
</aa>

Given that I cannot change the format of the XML I am receiving, is there a way to tell the XmlSerialiser to expect an array that is not wrapped inside another tag?

+3  A: 

Change your [XmlArray]/[XmlArrayItem] to [XmlElement], which tells the serializer the elements have no wrapper, e.g.

[XmlRoot("aa")]
public class aa
{
  [XmlElement("bb")]
  public bb[] bbs;
}

public class bb
{
  [XmlElement("name")]
  public string Name;
}
Greg Beech
+4  A: 

Try replacing your [XmlArray("bbs")] and [XmlArrayItem("bb")] attributes with a single [XmlElement] attribute

[XmlRoot("aa")]
public class aa
{
  [XmlElement("bb")]
  public bb[] bbs;
}

public class bb
{
  [XmlElement("name")]
  public string Name;
}

By putting the Array and ArrayItem attributes in, you were explicitly describing how to serialize this as an array with a wrapping container.

Rob Levine
Perfect, thanks
Dan