开发者

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

[开发者_如何学JAVAXmlRoot("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?


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.


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜