Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate XML from a class

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.

like image 916
DarthVader Avatar asked Jan 29 '26 06:01

DarthVader


2 Answers

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.

like image 148
carlosfigueira Avatar answered Jan 30 '26 19:01

carlosfigueira


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.

like image 24
Nick Zimmerman Avatar answered Jan 30 '26 19:01

Nick Zimmerman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!