我正在尝试使用字符串属性创建用于序列化/反序列化的c#对象。 该属性需要生成一个元素,并且还有一个属性:
例如:
...
<Comment Name="CommentName"></Comment>
...
如果属性是字符串,我无法看到如何添加属性,如果注释是具有Name和Value属性的对象,则会生成:
...
<Comment Name="CommentName">
<Value>comment value</Value>
</Comment>
...
有什么想法吗?
答案 0 :(得分:6)
您需要在类型上公开这两个属性,并使用[XmlText]
属性来指示它不应生成额外元素:
using System;
using System.Xml.Serialization;
public class Comment
{
[XmlAttribute]
public string Name { get; set; }
[XmlText]
public string Value { get; set; }
}
public class Customer
{
public int Id { get; set; }
public Comment Comment { get; set; }
}
static class Program
{
static void Main()
{
Customer cust = new Customer { Id = 1234,
Comment = new Comment { Name = "abc", Value = "def"}};
new XmlSerializer(cust.GetType()).Serialize(
Console.Out, cust);
}
}
如果要将这些属性展平到对象本身(我的示例中的Customer
实例),则需要额外的代码来使对象模型假装适合XmlSerializer
想要的内容,或者完全分离DTO模型。