views:

33

answers:

3

Can anyone tell me why my output is duplicating the 'FirstNode'?

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;

class Program
{
    static void Main(string[] args)
    {
        Root root = new Root();
        FirstNode firstNode = new FirstNode();
        firstNode.Data = "DATA";

        root.FirstNode.Add(firstNode);

        XmlSerializer s = new XmlSerializer(typeof(Root));
        StringWriter sw = new StringWriter();
        s.Serialize(sw, root);
        string serializedXml = sw.ToString();
        Console.WriteLine(serializedXml);
        Console.ReadKey();
    }
}

public class Root
{
    List<FirstNode> firstNode = new List<FirstNode>();

    public List<FirstNode> FirstNode
    {
        get { return firstNode; }
        set { firstNode = value; }
    }
}

public class FirstNode
{
    string data;
    public string Data
    {
        get { return data; }
        set { data = value; }
    }
}

OUTPUT

<Root>
  <FirstNode>
    <FirstNode>
      <Data>DATA</Data>
     </FirstNode>
  </FirstNode>
</Root>

Expected Output

<Root>
   <FirstNode>
      <Data>DATA</Data>
   </FirstNode>
</Root>
+1  A: 

Well if you look you have a Property Named FirstNode where you are storing your list, and inside the List you are storing FirstNode object... If you want to see it just change the name of the property FirstNode in the class Root to Nodes and you will see a differnet output

    <Root>  
      <Nodes>    
       <FirstNode>   
           <Data>DATA</Data>
       </FirstNode>  
      </Nodes>
</Root>

The Root tag appears because is the Object Type, as well as the FirsNode , then you have tags like Data and Nodes( in my case) because are the serialized properties of these classes

jmayor
A: 

Think it is this line:

   root.FirstNode.Add(firstNode);

You are adding a first node to a first node and therefore getting two layers of first node.

Shiraz Bhaiji
A: 

You want:

[XmlElement("FirstNode")]
public List<FirstNode> FirstNode
{
    get { return firstNode; }
    set { firstNode = value; }
}

This will only add <FirstNode> for the content items - not the list itself. You might also want to look at [XmlArray] / [XmlArrayItem] if you want finer control.

Marc Gravell