带有Name属性的C#XML字符串元素
我试图创建一个c#对象,用于使用string属性进行序列化/反序列化。 该属性需要生成一个元素并具有一个属性: 例如:带有Name属性的C#XML字符串元素,c#,xml-serialization,xml-deserialization,C#,Xml Serialization,Xml Deserialization,我试图创建一个c#对象,用于使用string属性进行序列化/反序列化。 该属性需要生成一个元素并具有一个属性: 例如: 。。。 ... 如果属性是字符串,我看不出如何添加属性,如果注释是一个具有名称和值属性的对象,它将生成: ... <Comment Name="CommentName"> <Value>comment value</Value> </Comment> ... 。。。 注释值 ... 有什么想法吗?您需要在一个类型上公
。。。
...
如果属性是字符串,我看不出如何添加属性,如果注释是一个具有名称和值属性的对象,它将生成:
...
<Comment Name="CommentName">
<Value>comment value</Value>
</Comment>
...
。。。
注释值
...
有什么想法吗?您需要在一个类型上公开这两个属性,并使用
[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模型
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);
}
}