using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Linq;
namespace Serialize
{
public class Good
{
public int a;
public Good() {}
public Good(int x)
{
a = x;
}
}
public class Hello
{
public int x;
public List<Good> goods = new List<Good>();
public Hello()
{
goods.Add(new Good(1));
goods.Add(new Good(2));
}
}
[XmlRootAttribute("Component", IsNullable = false)]
public class Component {
//[XmlElement("worlds_wola", IsNullable = false)]
public List<Hello> worlds;
public Component()
{
worlds = new List<Hello>() {new Hello(), new Hello()};
}
}
class Cov2xml
{
static void Main(string[] args)
{
string xmlFileName = "ip-xact.xml";
Component comp = new Component();
TextWriter writeFileStream = new StreamWriter(xmlFileName);
var ser = new XmlSerializer(typeof(Component));
ser.Serialize(writeFileStream, comp);
writeFileStream.Close();
}
}
}
With this XmlSerializer code, I get this XML file.

I have only one “worlds” element, that has two Hello elements.
However, when I add XmlElement before the worlds varibale.
[XmlElement("worlds_wola", IsNullable = false)]
public List<Hello> worlds
I have two worlds_wola elements instead of one.

Why is this? How can I use XmlElement to specify the name of the tag, but with only one “worlds_wola” element as follows?
<worlds_wola>
<Hello>
...
</Hello>
<Hello>
...
</Hello>
</worlds_wola>
You need to use the XmlArrayAttribute for your collection instead of the XmlElementAttribute.