views:

228

answers:

1

Hi,

I am trying to create a c# object for serialization/deserialization with a string property. 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:

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

Any ideas?

+3  A: 

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:

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.

Marc Gravell