user15486
user15486

Reputation:

How to add an XML sub-element to a simple data type in C#

I'm trying to serialize a simple data type into XML, but in a particular way to satisfy an existing API. (assume that the desired XML must be formed in this way)

Here is the desired XML:

<foo>
<value>derp</value>
</foo>

I would ideally like to represent this in a class as just

String foo;

The only two options I know of are

  1. Simple serialization, which of course just leads to
    <foo>derp</foo>
  1. creating a Foo class, which creates the desired XML, but forces the user to type
    myFoo.Value = "derp";

instead of the preferable

foo = "derp";

Is there any way to have the simple string in the class, but represent it with the <value> sub-element?

Upvotes: 1

Views: 168

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

Use this implementation:

[XmlRoot("foo")]
public class Foo
{
    [XmlElement("value")]
    public string Value { get; set; }

    public static implicit operator Foo(string s)
    {
        return new Foo { Value = s };
    }
}

Usage:

private static void Main()
{
    Foo foo = "abc";

    var ns = new XmlSerializerNamespaces();
    ns.Add(string.Empty, string.Empty);

    var serialzier = new XmlSerializer(typeof(Foo));

    using (var writer = new StringWriter())
    {
        serialzier.Serialize(writer, foo, ns);

        Console.WriteLine(writer.ToString());
    }
}

Output:

<?xml version="1.0" encoding="utf-16"?>
<foo>
  <value>abc</value>
</foo>

Upvotes: 5

Related Questions