使用c# XmlSerializer将父元素名继承到子元素中
本文关键字:元素 继承 使用 XmlSerializer | 更新日期: 2023-09-27 18:15:47
我有一个类,看起来像这样:
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元素的名称在子元素名称前加上前缀。
试试这个
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; }
}
}