some value How should a class ...">

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.


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
        public string Value { set; get; }
        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);


Update : Added code to serialize the type.



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 for details .



All Articles