gpt4 book ai didi

c# - 序列化 XML 时更改元素的顺序

转载 作者:IT王子 更新时间:2023-10-29 04:30:48 25 4
gpt4 key购买 nike

我需要将对象序列化为 XML 并返回。 XML 已修复,我无法更改它。我无法在 bookingList 之后生成此结构。

我如何“分组”这些 <booking> 元素以显示为 LIST,并在这个 <error> 元素列表之前保留 <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; }
}
}

最佳答案

尝试用 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>

相关资源:

关于c# - 序列化 XML 时更改元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6455067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com