简体   繁体   English

具有Name属性的C#XML字符串元素

[英]C# XML string element with Name attribute

I am trying to create ac# object for serialization/deserialization with a string property. 我正在尝试使用字符串属性创建用于序列化/反序列化的ac#对象。 The property needs to generate an element and also have an attribute: 该属性需要生成一个元素,并且还具有一个属性:

eg: 例如:

...
<Comment Name="CommentName"></Comment>
...

If the property is a string, I cant see how to add the attribute, and if the comment is an object with Name and Value properties it generates: 如果该属性是字符串,则看不到如何添加该属性,并且如果注释是具有Name和Value属性的对象,它将生成:

...
<Comment Name="CommentName">
    <Value>comment value</Value>
</Comment>
...

Any ideas? 有任何想法吗?

You would need to expose those 2 properties on a type and use the [XmlText] attribute to indicate that it shouldn't generate an extra element: 您将需要在类型上公开这两个属性,并使用[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);
    }
}

If you want to flatten those properties onto the object itself (the Customer instance in my example), you would need extra code to make the object model pretend to fit what XmlSerializer wants, or a completely separate DTO model. 如果要将这些属性放到对象本身(在我的示例中为Customer实例)上,则需要额外的代码来使对象模型假装成适合XmlSerializer想要的对象,或者是完全独立的DTO模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM