Generating XML from a class
I want to create the following XML node from a class.
<Foo id="bar">some value</Foo>
How should a class be defined?
class Foo
{
public string Value {set;get;}
public string id{set;get;}
}
I believe I should put some XML attributes in these properties, but not sure what they are.
+2
DarthVader
source
to share
2 answers
Take a look at the attributes in the System.Xml.Serialization namespace. In your case, the class should look like this.
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.
+9
carlosfigueira
source
to share
For C # and Visual Basic, there is no reason to do this manually. Visual Studio includes a command line tool that will generate a class diagram or xml for you. See http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=VS.100).aspx for details .
+2
Nick zimmerman
source
to share