名单的XML序列化名单、序列化、XML

2023-09-03 17:46:30 作者:夜袭寡妇村

我序列化对象到XML。我有这样的事情:

I am serializing an object to XML. I have something like this:

Class A
{
   public string propertyA1  { get; set; }
   public List<B> bList { get; set; }
}

Class B
{
   public string num {get; set;}
   public string propertyB1  { get; set; }
}

当我把它序列化到XML,我希望它看起来是这样的:

When I serialize it to XML, I want it to look like this:

<A>
  <propertyA1>someVal</propertyA1> 
  <B num=1>
     <propertyB1>someVal</propertyB1> 
  </B>
  <B num=2>
     <propertyB1>someVal</propertyB1> 
  </B>
</A>

但是,相反,它看起来是这样的:

But, instead it looks like this:

<A>
  <propertyA1>someVal</propertyA1> 
  <bList>
     <B num=1>
        <propertyB1>someVal</propertyB1> 
     </B>
     <B num=2>
        <propertyB1>someVal</propertyB1> 
     </B>
  </bList>
</A>

任何想法如何让输出摆脱 bList ?如果需要,我可以提供更多的样品code

Any idea how to get rid of the bList in the output? I can provide more sample code if needed

谢谢, 斯科特

推荐答案

添加属性 [的XmlElement] 来对待集合为元素的简单列表:

Add the attribute [XmlElement] to treat the collection as a flat list of elements:

Class A
{
   public string propertyA1  { get; set; }
   [XmlElement("B")]
   public List<B> bList { get; set; }
}

有关更多信息请点击这里