Using Xml Linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
TestObject tests = new TestObject() {
Actions = new List<Action>() {
new Action() { Name = "A", Type = "Dog"},
new Action() { Name = "C", Type = "Cat"},
new Action() { Name = "E", Type = "Elephant"}
}
};
string root = "<TestObject></TestObject>";
XDocument doc = XDocument.Parse(root);
XElement testObject = doc.Root;
int index = 0;
foreach (Action action in tests.Actions)
{
XElement newAction = new XElement("Action" + index.ToString(), new object[] {
new XElement("Name", action.Name),
new XElement("Type", action.Type)
});
testObject.Add(newAction);
index++;
}
doc.Save(FILENAME);
}
}
public class Action
{
public string Name;
public string Type;
}
public class TestObject
{
public List<Action> Actions;
}
}
Using a Custom Xml Serializer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Xml.Schema;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
TestObject tests = new TestObject() {
Actions = new List<Action>() {
new Action() { Name = "A", Type = "Dog"},
new Action() { Name = "C", Type = "Cat"},
new Action() { Name = "E", Type = "Elephant"}
}
};
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(FILENAME,settings);
XmlSerializer serializer = new XmlSerializer(typeof(TestObject));
serializer.Serialize(writer, tests);
}
}
public class Action
{
public string Name;
public string Type;
}
public class TestObject : IXmlSerializable
{
public List<Action> Actions;
public void WriteXml(XmlWriter writer)
{
List<XElement> testObjects = new List<XElement>();
int index = 0;
foreach (Action action in Actions)
{
XElement newAction = new XElement("Action" + index.ToString(), new object[] {
new XElement("Name", action.Name),
new XElement("Type", action.Type)
});
testObjects.Add(newAction);
index++;
}
string obj = string.Join("", testObjects.Select(x => x.ToString()));
writer.WriteRaw("\n" + obj + "\n");
}
public void ReadXml(XmlReader reader)
{
}
public XmlSchema GetSchema()
{
return (null);
}
}
}
Actionelement differently, when they are stored in a list?