C # XML String Element with Name Attribute

I am trying to create a C # object for serialization / deserialization using the string property. The property must generate an element and also have an attribute:

eg:

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

If the property is a string, I don’t see how to add this attribute, and if the comment is an object with the Name and Value properties, it generates:

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

Any ideas?

+5
source share
1 answer

You will need to open these 2 properties for the type and use the attribute [XmlText]to indicate that it should not generate an additional element:

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.

+6

All Articles