2

我已经使用这篇文章将我的字典转换为 xml:

将 Dictionary<string, string> 转换为 xml 的简单方法,反之亦然

我在做什么:

Dictionary<int, string> dicEntityRules = new Dictionary<int, string>();
// add the items to dicEntityRules    

DataContractSerializer serializer = new DataContractSerializer(dicEntityRules.GetType());

         using (StringWriter sw = new StringWriter())
         {
             using (XmlTextWriter writer = new XmlTextWriter(sw))
             {                    
                 writer.Formatting = Formatting.Indented;

                 serializer.WriteObject(writer, dicEntityRules);

                 writer.Flush();

                 sw.ToString();
             }

         }

但是,我的 xml 是这样的:

<KeyValueOfintstring>
    <Key>2048</Key>
    <Value>66</Value>
  </KeyValueOfintstring>

我可以更改此节点/属性名称吗?

我想要一些这样的:

     <Order>
        <entity>2048</entity>
        <rule>66</rule>
      </Order>

问候。

墨菲 [[|]] 的

4

1 回答 1

2

将您的字典转换为 aList<Order>并将其序列化:

void Main()
{
    var dicEntityRules = new Dictionary<int, string>();

    dicEntityRules.Add(1, "One");

    // Convert to List<Order>
    var orders = dicEntityRules.Select (er => 
        new Order {entity=er.Key, rule=er.Value}).ToList();

    var serializer = new DataContractSerializer(typeof(List<Order>));

    using (var sw = new StringWriter())
    {
        using (XmlTextWriter writer = new XmlTextWriter(sw))
        {                    
            writer.Formatting = Formatting.Indented;

            serializer.WriteObject(writer, orders);

            writer.Flush();

            var s = sw.ToString();
        }
    }
}

[DataContract()]
public class Order
{
    [DataMember]
    public int entity { get; set; }
    [DataMember]
    public string rule { get; set; }
}
于 2012-04-10T20:24:33.130 回答