Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XML string element with Name attribute

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?

like image 344
Mark Redman Avatar asked Jan 18 '10 12:01

Mark Redman


1 Answers

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.

like image 145
Marc Gravell Avatar answered Nov 20 '22 06:11

Marc Gravell