Попробуйте следующее:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
List<Department> departments = new List<Department>() {
new Department() { Name = "IT", Number = "1", SubDepartments = new List<Department>() {
new Department() { Name = "Software engineering", Number = "1.1", SubDepartments = new List<Department>() {
new Department() { Name = "Quality assurnace", Number = "1.1.1"},
new Department() { Name = "Development", Number = "1.1.2"}
}},
new Department() { Name = "Support", Number = "1.2"},
new Department() { Name = "Administration", Number = "1.3"}
}},
new Department() { Name = "Finance", Number = "2", SubDepartments = new List<Department>() {
new Department() { Name = "Accounting", Number = "2.1"}
}}
};
string header = "<Company></Company>";
XDocument doc = XDocument.Parse(header);
XElement company = doc.Root;
int level = 1;
CreateXml(departments, company, level);
doc.Save(FILENAME);
}
static void CreateXml(List<Department> parentDept, XElement parentXml, int level)
{
foreach (Department department in parentDept)
{
XElement newDept;
if (level == 1)
{
newDept = new XElement("MainDepartment");
}
else
{
newDept = new XElement("SubDepartment");
}
parentXml.Add(newDept);
newDept.Add(new XAttribute("name", department.Name));
newDept.Add(new XAttribute("number", department.Number));
if (department.SubDepartments != null)
{
CreateXml(department.SubDepartments, newDept, level + 1);
}
}
}
}
public class Department
{
public string Name { get; set; }
public string Number { get; set; }
public List<Department> SubDepartments { get; set; }
}
}