Reputation: 55132
I want to build the following XML node from a class.
<Foo id="bar">some value</Foo>
How should my class definition be?
class Foo
{
public string Value {set;get;}
public string id{set;get;}
}
I believe i should put some XML attributes to these properties but not sure what they are.
Upvotes: 2
Views: 1472
Reputation: 1531
For C# and Visual Basic, there is no reason to do this by hand. Visual Studio includes a command line tool that will generate the class or xml schema for you. See http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=VS.100).aspx for details.
Upvotes: 3
Reputation: 87323
Take a look at the attributes under the System.Xml.Serialization namespace for that. In your case, the class should look like the code below.
public class StackOverflow_8281703
{
[XmlType(Namespace = "")]
public class Foo
{
[XmlText]
public string Value { set; get; }
[XmlAttribute]
public string id { set; get; }
}
public static void Test()
{
MemoryStream ms = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Foo));
Foo foo = new Foo { id = "bar", Value = "some value" };
xs.Serialize(ms, foo);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
}
Update: added code to serialize the type.
Upvotes: 9