public class Person { public string Address { get; set; } public string Name { get; set; } } public static string ToXml(List<Person> people) { var sw = new System.IO.StringWriter(); var xw = new System.Xml.XmlTextWriter(sw); xw.Formatting = System.Xml.Formatting.Indented; xw.Indentation = 4; xw.WriteStartElement("xml"); var oldAddress = ""; var firstPass = true; foreach (var person in people) { if (!firstPass && person.Address != oldAddress) xw.WriteEndElement(); // </address> if (firstPass || person.Address != oldAddress) { xw.WriteStartElement("address"); xw.WriteAttributeString("id", person.Address); } xw.WriteStartElement("name"); xw.WriteAttributeString("id", person.Name); xw.WriteEndElement(); // </name> firstPass = false; oldAddress = person.Address; } xw.WriteEndElement(); // </address> xw.WriteEndElement(); // </xml> return sw.ToString(); }