// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; namespace XmlProc.Write { public class Employee { public Employee() : this(0, "", "") { } public Employee(int no, string name, string role) { this.No = no; this.Name = name; this.Role = role; } public int No { get; set; } public string Name { get; set; } public string Role { get; set; } public override string ToString() { return string.Format("[{0},{1},{2}]", No, Name, Role); } } public class Employees { public List EmployeeList { get; set; } public Employees() { this.EmployeeList = new List(); } public override string ToString() { return "{" + string.Join(",", EmployeeList.ConvertAll(e => e.ToString()).ToArray()) + "}"; } } public class Program { public static void Main(string[] args) { // create employees Employees employees = new Employees(); employees.EmployeeList.Add(new Employee(1, "Alan A", "Manager")); employees.EmployeeList.Add(new Employee(2, "Brian B", "Engineer")); employees.EmployeeList.Add(new Employee(3, "Chris C", "Sales rep")); employees.EmployeeList.Add(new Employee(4, "Dave D", "Intern")); // write out using(StreamWriter sw = new StreamWriter(@"C:\work\employees2.xml")) { XmlWriterSettings xws = new XmlWriterSettings(); xws.Indent = true; XmlWriter xw = XmlWriter.Create(sw, xws); xw.WriteStartDocument(); xw.WriteStartElement("employees"); foreach(Employee employee in employees.EmployeeList) { xw.WriteStartElement("employee"); xw.WriteAttributeString("no", employee.No.ToString()); xw.WriteStartElement("name"); xw.WriteString(employee.Name); xw.WriteEndElement(); xw.WriteStartElement("role"); xw.WriteString(employee.Role); xw.WriteEndElement(); xw.WriteEndElement(); } xw.WriteEndElement(); xw.WriteEndDocument(); xw.Close(); } } } }