BWHazel
BWHazel

Reputation: 1474

In XML serialisation, can properties be serialised as an attribute of a new element?

I have a class with a similar structure to:

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement("subject")]
    public string Subject { get; set; }

    [XmlElement("object")]
    public string Object { get; set; }
}

Assuming Subject = "Me" and Object = "You", this would serialise to:

<myclass>
  <subject>Me</subject>
  <object>You</object>
</myclass>

Is there a way to serialise to the following XML, preferably using XML serialisation attributes and avoiding new custom types:

<myclass>
  <subject value="Me" />
  <object value="You" />
</myclass>

Upvotes: 1

Views: 47

Answers (1)

Tim S.
Tim S.

Reputation: 56536

You can do this by creating a class that uses the XmlAttributeAttribute. I included implicit conversion from T so that you can continue to use concise syntax like new MyClass { Subject = "Me", Object = "You" }

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement("subject")]
    public ValueAttribute<string> Subject { get; set; }

    [XmlElement("object")]
    public ValueAttribute<string> Object { get; set; }
}
public class ValueAttribute<T>
{
    [XmlAttribute("value")]
    public T Value { get; set; }

    public static implicit operator ValueAttribute<T>(T value)
    {
        return new ValueAttribute<T> { Value = value };
    }
}

This produces something like:

<?xml version="1.0" encoding="utf-16"?>
<myclass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <subject value="Me" />
  <object value="You" />
</myclass> 

Upvotes: 2

Related Questions