序列化XML时更改元素的顺序

编程入门 行业动态 更新时间:2024-10-28 02:26:35
本文介绍了序列化XML时更改元素的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I need to serialize an Object to XML and back. The XML is fix and I can't change it. I fail to generate this structure after bookingList.

如何将这些<booking>元素分组"以显示为LIST并保持<error>& <counter>在此<booking>元素列表之前.

How can I "group" these <booking> elements to appear as a LIST and keep <error> & <counter> before this List of <booking> elements.

在这里查看我的示例:

我需要的结构....

<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#代码获得的结构....

Structure i get with C# code below....

<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 ,以便控制该类的对象如何将序列化为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; } }

在我的测试中,我获得了以下输出:

In my test I obtained this output:

<?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>

相关资源:

  • 使用属性控制XML序列化

更多推荐

序列化XML时更改元素的顺序

本文发布于:2023-11-09 16:09:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572827.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   元素   序列化   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!