简体   繁体   English

带有双xml标签的序列化xml,其中顺序在c#中很重要

[英]Serialization xml with double xml tags where order is important in c#

I want to serialize xml which works but I have a problem.我想序列化有效的xml,但我有一个问题。 Sometimes I have the same tag multiple times but on different places.有时我有多次相同的标签,但在不同的地方。 So the order is important so I cant just stick it in an list.所以顺序很重要,所以我不能把它放在一个列表中。

For example I have the following xml:例如,我有以下 xml:

<?xml version="1.0" encoding="utf-16"?>
<commands>
    <execute>some statement</execute>
    <wait>5</wait>
    <execute>some statement</execute>
    <wait>5</wait>
    <execute>some statement</execute>
    <execute>some statement</execute>
</commands>

Then my object would look something like this:然后我的对象看起来像这样:

[XmlRoot(ElementName="commands")]
public class Commands { 

    [XmlElement(ElementName="execute")] 
    public List<string> Execute { get; set; } 

    [XmlElement(ElementName="wait")] 
    public List<int> Wait { get; set; } 
}

If I then serialize it with the following function:如果我然后使用以下函数对其进行序列化:

var xmlSerializer = new XmlSerializer(obj.GetType());

using (var writer = new Utf8StringWriter())
{
  xmlSerializer.Serialize(writer, obj);
  return writer.ToString();
}

The order will not be the same.... It would first serialize the execute tags and then the wait statements.顺序将不一样......它将首先序列化执行标签,然后是等待语句。 While the order is important.虽然顺序很重要。

Does someone have a clue on how to tackle this problem?有人知道如何解决这个问题吗?

Ps.附言。 changing the xml is not a solution as I'm tied to that....更改 xml 不是解决方案,因为我与此相关......

Thanks in advance!提前致谢!

After searching for a while I tackle the problem as the following.经过一段时间的搜索,我解决了以下问题。 The wait and execute are basically commands to I serialize now a list of commands.等待和执行基本上是我现在序列化命令列表的命令。 Of course the seriliazer will complain that it can't serlize this because it is a list of interfaces (ICommand) so I implemented the IXmlSerliazer so that I tell how to serliaze this.当然,序列化器会抱怨它不能序列化它,因为它是一个接口列表(ICommand),所以我实现了 IXmlSerliazer 以便我告诉如何序列化它。

This worked actually quite good这实际上工作得很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM