Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how can I deserialize an XML document containing a list of elements without a surrounding list element

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?

like image 938
Dan Avatar asked Jan 06 '10 11:01

Dan


People also ask

What does << mean in C?

<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .

What is && operator in C?

The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int . Both operands must have an arithmetic or pointer type.


2 Answers

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.

like image 81
Rob Levine Avatar answered Oct 20 '22 05:10

Rob Levine


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;
}
like image 30
Greg Beech Avatar answered Oct 20 '22 06:10

Greg Beech