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?
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With