[英]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:
我有一个小的XML文档,看起来大致如下:
<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 我有代表aa和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. 当我尝试使用XmlSerializer反序列化文档时,我得到一个具有null bbs属性的对象。 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:
据我所知,这是因为我在bbs属性上使用的属性告诉序列化程序期望这样的文档:
<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? 鉴于我无法更改我收到的XML格式,有没有办法告诉XmlSerialiser期望一个未包装在另一个标签内的数组?
Try replacing your [XmlArray("bbs")]
and [XmlArrayItem("bb")]
attributes with a single [XmlElement] attribute 尝试使用单个[XmlElement]属性替换
[XmlArray("bbs")]
和[XmlArrayItem("bb")]
]属性
[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. 通过放入
Array
和ArrayItem
属性,您明确地描述了如何将其序列化为带有包装容器的数组。
Change your [XmlArray]
/ [XmlArrayItem]
to [XmlElement]
, which tells the serializer the elements have no wrapper, eg 将
[XmlArray]
/ [XmlArrayItem]
更改为[XmlElement]
,它告诉序列化程序元素没有包装器,例如
[XmlRoot("aa")]
public class aa
{
[XmlElement("bb")]
public bb[] bbs;
}
public class bb
{
[XmlElement("name")]
public string Name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.