Reputation:
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
<foo>derp</foo>
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
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