使用C#XmlSerializer将父元素名称继承到子级

时间:2016-10-31 20:06:26

标签: c# xml xml-serialization xmlserializer

我有一个看起来像这样的课程:

public class CustomerType 
{
    public string Address {get; set;}
    public string City {get; set;}
}

还有另外一个类:

public class CustomerInfo
{
        public CustomerType Sender {get; set;}
        public CustomerType Reciever {get; set;}
}

如何配置XmlSerializer以便获取以下XML?

<CustomerInfo>
   <Sender>
       <SenderAddress></SenderAddress> 
       <SenderCity></SenderCity>
   </Sender> 
   <Receiver>
       <ReceiverAddress></ReceiverAddress> 
       <ReceiverCity></ReceiverCity>
   </Receiver> 
</CustomerInfo>

我正在使用的API需要这种格式化,即序列化时,CustomerType元素的名称会以子元素名称为前缀。

1 个答案:

答案 0 :(得分:0)

试试这个

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            CustomerInfo info = new CustomerInfo()
            {
                Sender = new CustomerSender()
                {
                    Address = "123",
                    City = "North Pole"
                },
                Reciever = new CustomerReceiver()
                {
                    Address = "456",
                    City = "South Pole"
                }
            };

            XmlSerializer serializer = new XmlSerializer(typeof(CustomerInfo));

            StreamWriter writer = new StreamWriter(FILENAME);
            serializer.Serialize(writer, info);
            writer.Flush();
            writer.Close();
            writer.Dispose();

        }
    }
    [XmlRoot("Sender")]
    public class CustomerSender
    {
        [XmlElement("SenderAddress")]
        public string Address { get; set; }

        [XmlElement("SenderCity")]
        public string City { get; set; }
    }
    [XmlRoot("Receiver")]
    public class CustomerReceiver
    {
        [XmlElement("ReceiverAddress")]
        public string Address { get; set; }

        [XmlElement("ReceiverCity")]
        public string City { get; set; }
    }
    public class CustomerInfo
    {
        [XmlElement("Sender")]
        public CustomerSender Sender { get; set; }

        [XmlElement("Receiver")]
        public CustomerReceiver Reciever { get; set; }
    }
}