1

我正在尝试将以下类序列化为 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>
4

3 回答 3

1

您可以使用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));
    }
}

代码示例未经测试

于 2013-08-26T17:24:15.680 回答
0

将项目表示为相关,例如,List<KeyValuePair<ScheduleXml, TimeTableXml>>如果您希望项目配对。

于 2013-08-26T17:23:10.110 回答
0

有了有用的答案和评论,我最终能够得到正确的解决方案。我在这里发布我所做的事情,以帮助面临类似问题的其他人。

如果您开始使用 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 序列化标记了两个类。

于 2013-08-27T14:55:46.240 回答