views:

154

answers:

1

I have a custom XML (Vendor specific) which I need to serialize and deserialize. The format of the XML is as follows

<RootElement> 
    <childelement>              
         <id/>
          <description/>
    </childelement>
    <childelement>
         <id/>
         <description/>
    </childelement>
</RootElement>
  • Root element is also and Object which contains a list of child elements
  • Child element is defined as an object

Note that I dont want the childelements to be encapsulated by another tag . Sorry this is not my XML design :)

+1  A: 

Here is an example using C#. Here is an example if you need to use XML namespaces.

[XmlRoot("RootElement")]
public class MyObject
{
    [XmlElement("childelement")]
    public MyChild[] Children { get; set; }
}
public class MyChild
{
    [XmlElement("id")]
    public int ID { get; set; }
    [XmlElement("description")]
    public string Description { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var xser = new XmlSerializer(typeof(MyObject));
        using (var ms = new MemoryStream())
        {
            var myObj = new MyObject()
            {
                Children = new[]{
                    new MyChild(){ ID=0, Description="Hello"},
                    new MyChild(){ ID=1, Description="World"}
                }
            };
            xser.Serialize(ms, myObj);
            var res = Encoding.ASCII.GetString(ms.ToArray());
            /*
                <?xml version="1.0"?>
                <RootElement>
                  <childelement>
                    <id>0</id>
                    <description>Hello</description>
                  </childelement>
                  <childelement>
                    <id>1</id>
                    <description>World</description>
                  </childelement>
                </RootElement>
             */
        }
    }
}
Matthew Whited