如何将c#Entity的相同标签转换为Xml

时间:2014-09-19 03:24:56

标签: c# xml xmlserializer

我有疑问!!

=============正常===========

class trx()
{
   string trx_name;
   string type_id;
}

var 0 = new trx(){trx_name="1",trx_name="2"}

---实体更改为xml

[XmlSerializer serializer = new XmlSerializer(typeof(trx));
[serializer.Serialize(File.OpenWrite(@".\MyXml.xml"), o);]

---- XML结果------

<trx>
  <trx_name>1</trx_name> 
  <type_id>2</type_id> 
</trx>

=============================

问:但我需要trx XML

<trx>
  <trx_name>a</trx_name> 
  <trx_name>b</trx_name> 
  <trx_name>c</trx_name> 
  <trx_name>d</trx_name> 
</trx>

如何解决问题?

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

像这样。

 public class trx
    {
        public string trx_name { get; set; }
    }

    public class CustomSerializer
    {
        private static void Write(string filename)
        {
            List<trx> trxs = new List<trx>();
            trxs.Add(new trx {trx_name = "Name1"});
            trxs.Add(new trx {trx_name = "Name2"});
            XmlSerializer x = new XmlSerializer(typeof (List<trx>));
            TextWriter writer = new StreamWriter(filename);
            x.Serialize(writer, trxs);
        }

        private static List<trx> Read(string filename)
        {
            var x = new XmlSerializer(typeof (List<trx>));
            TextReader reader = new StreamReader(filename);
            return (List<trx>) x.Deserialize(reader);
        }
    }
}