我需要将Object序列化为XML并返回。 XML已修复,我无法更改它。
我在bookingList
之后无法生成此结构。
如何将这些<booking>
元素“分组”显示为列表并保留<error>
&amp;此<counter>
元素列表之前的<booking>
。
请参阅我的示例:
我需要的结构......
<nicexml>
<key_id>1234567</key_id>
<surname>Jil</surname>
<name>Sander</name>
<station_id>1</station_id>
<ownBookings>
<bookingList>
<error></error>
<counter>20</counter>
<booking>
<bookingID>1234567890</bookingID>
</booking>
<booking>
<bookingID>2345678901</bookingID>
</booking>
</bookingList>
</ownBookings>
</nicexml>
结构我得到了下面的C#代码......
<nicexml>
<key_id>1234567</key_id>
<surname>Jil</surname>
<name>Sander</name>
<station_id>1</station_id>
<ownBookings>
<bookingList>
<booking>
<booking>
<bookingID>1234567890</bookingID>
</booking>
<booking>
<bookingID>2345678901</bookingID>
</booking>
<booking>
<error></error>
<counter>20</counter>
</bookingList>
</ownBookings>
</nicexml>
C#代码:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace xml_objects_serials
{
public class bookings
{
public class nicexml
{
public string key_id
{ get; set; }
public string surname
{ get; set; }
public string name
{ get; set; }
public int station_id
{ get; set; }
public ownBookings ownBookings
{ get; set; }
}
public class ownBookings
{
public bookingList bookingList
{ get; set; }
}
public class bookingList {
public string error
{ get; set; }
public int counter
{ get; set; }
public List<booking> booking= new List<booking>();
}
public class booking
{
public int bookingID
{ get; set; }
}
}
答案 0 :(得分:31)
尝试使用XmlElementAttribute修饰bookingList
类的属性,以便控制该类的对象将如何序列化为XML 。
以下是一个例子:
public class bookingList
{
[XmlElement(Order = 1)]
public string error { get; set; }
[XmlElement(Order = 2)]
public int counter { get; set; }
[XmlElement(ElementName = "booking", Order = 3)]
public List<booking> bookings = new List<booking>();
}
public class booking
{
public int id { get; set; }
}
在我的测试中,我获得了这个输出:
<?xml version="1.0" ?>
<bookingList>
<error>sample</error>
<counter>0</counter>
<booking>
<id>1</id>
</booking>
<booking>
<id>2</id>
</booking>
<booking>
<id>3</id>
</booking>
</bookingList>
相关资源:
答案 1 :(得分:-3)
我遇到了这个问题,我解决了......好吧,这很有趣,这可能是.net中的一个错误。
问题在于:
public List<booking> booking= new List<booking>();
你应该使用:
public List<booking> booking { get; set; }
你将获得定义的订单....但为什么?谁知道...... :)