对象序列化为XML,其元素名称具有序列号

时间:2014-08-21 07:48:23

标签: c# xml asp.net-mvc

我已经实现了对象序列化,可以使用 XmlSerializer.Serialize(...)方法将我的对象转换为XML字符串。

目前,序列化程序正在生成以下XML:

<MyAddress>
  <row>
    <Home>1</Home>
    <Office>2</Office>
  </row>
  <row>
    <Home>1</Home>
    <Office>2</Office>
  </row>
  <row>
    <Home>1</Home>
    <Office>2</Office>
  </row>
</MyAddress>

但我希望生成以下XML:

<MyAddress>
  <row1>
    <Home>1</Home>
    <Office>2</Office>
  </row1>
  <row2>
    <Home>1</Home>
    <Office>2</Office>
  </row2>
  <row3>
    <Home>1</Home>
    <Office>2</Office>
  </row3>
</MyAddress>

我的C#代码中使用的类如下:

namespace MyApp
{
    public class MyAddress
    {
        public List<row> Rows { get; set; }
    }


    public class row
    {
        public string Home { get; set; }
        public string Office { get; set; }
    }
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我建议您使用XmlAttribute您的Row类来存储索引,然后对项目进行排序。这是一个例子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;

public class Program
{
    private static void Main(string[] args)
    {
        var address = new MyAddress();

        address.Rows = new List<Row>();

        var rows = new List<Row>();
        rows.Add(new Row { Home = "Home A" });
        rows.Add(new Row { Home = "Home B" });
        rows.Add(new Row { Home = "Home B" });

        var items = rows.Select((x, index) => new Row 
        {
            Home = x.Home,
            Office = x.Office,
            Index = ++index
        });

        address.Rows.AddRange(items);

        var xmlS = new XmlSerializer(typeof(MyAddress));
        xmlS.Serialize(Console.Out, address);
    }
}

public class MyAddress
{
    public MyAddress()
    {
        Rows = new List<Row>();
    }

    public List<Row> Rows { get; set; }
}

public class Row
{
    [XmlAttribute]
    public int Index { get; set; }

    public string Home { get; set; }

    public string Office { get; set; }
}

这应该会产生以下XML:

<MyAddress>
  <row Index="1">
    <Home>1</Home>
    <Office>2</Office>
  </row>
  <row Index="2">
    <Home>1</Home>
    <Office>2</Office>
  </row>
  <row Index="3">
    <Home>1</Home>
    <Office>2</Office>
  </row>
</MyAddress>