列表上的XML序列化控制顺序
本文关键字:控制 顺序 序列化 XML 列表 | 更新日期: 2023-09-27 18:29:01
我正在尝试将以下类序列化为XML:
[XmlRoot("FCS_SET_SCH")]
public class DDCSendReceiveScheduleXml
{
private const string TABLE_NAME = "DDCScheduler";
[XmlElement("schedule",Order=1)]
public List<ScheduleXml> ScheduleList { get; set; }
[XmlElement("timetable",Order=2)]
public List<TimeTableXml> TimeTableXmlList { get; set; }
public DDCSendReceiveScheduleXml()
{
}
}
若我要对每个对象序列化一个对象,则Order标志有效,但它似乎不能控制列表上的顺序。
这就是XmlSerializer目前序列化两个列表的方式:
<FCS_SET_SCH xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<schedule>...</schedule>
<schedule>...</schedule>
<timetable>...</timetable>
<timetable>...</timetable>
</FCS_SET_SCH>
有没有什么方法可以控制序列化,使以上内容按此顺序出现?
<FCS_SET_SCH xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<schedule>...</schedule>
<timetable>...</timetable>
<schedule>...</schedule>
<timetable>...</timetable>
</FCS_SET_SCH>
您可以使用ISerializable来获得对序列化过程的更多控制。当你输入接口时,你可以访问GetObjectData
方法
// Implement this method to serialize data. The method is called
// on serialization.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
var smallest = (TimeTableXmlList.Count < ScheduleList.Count ?? TimeTableXmlList.Count : ScheduleList.Count )
for(int x = 0; x < smallest; x++)
{
var time = TimeTableXmlList.ElementAt(x);
var schedule = ScheduleList.ElementAt(x)
// Use the AddValue method to specify serialized values.
info.AddValue("timetable", time, typeof(TimeTableXml));
info.AddValue("schedule", schedule , typeof(ScheduleXml));
}
}
代码示例是未经测试的
将项目表示为相关的,如果希望项目成对,则表示为List<KeyValuePair<ScheduleXml, TimeTableXml>>
。
有了有用的答案和评论,我终于找到了正确的解决方案。我在这里发布我所做的事情是为了帮助其他面临类似问题的人。
如果您首先使用XmlSerializer,那么实现IXmlSerializable是一种简单而正确的方法。
[XmlRoot("FCS_SET_SCH")]
public class DDCSendReceiveScheduleXml : IXmlSerializable
{
...
public XmlSchema GetSchema()
{
return null;
}
public void WriteXml(XmlWriter writer)
{
Debug.Assert(ScheduleList.Count == TimeTableXmlList.Count, "ScheduleList and TimeTableXml Count isn't same");
XmlSerializer scheduleSerializer = new XmlSerializer(typeof(ScheduleXml));
XmlSerializer timeTableSerializer = new XmlSerializer(typeof(TimeTableXml));
for (int i = 0; i < ScheduleList.Count; i++)
{
scheduleSerializer.Serialize(writer, ScheduleList[i]);
timeTableSerializer.Serialize(writer, TimeTableXmlList[i]);
}
}
这产生了我最初想要的结果。当然,这假设您已经为Xml序列化标记了两个类。