>>List<string> MyList = new List<string>(); >>MyList.Add( "ABC" ); >>MyList.Add( "CBS" ); >>MyList.Add( "NBC" ); >> >>// Now I want to write the above list to an XML that will look like this: >><?xml version="1.0"?> >><Choices> >> <Channel>ABC</Channel> >> <Channel>CBS</Channel> >> <Channel>NBC</Channel> >></Choices> >>>>
List<string> channels = new List<string> {"ABC", "CBS", "NBC"}; > XmlDocument xd = new XmlDocument(); > var choices = xd.AppendChild(xd.CreateElement("Choices")); > foreach (String s in channels) > { > var channel = xd.CreateElement("Channel"); > channel.InnerText = s; > choices.AppendChild(channel); > } > xd.Save(@"d:\test.xml");Or you could look at XmlSerializer and adding attributes to classes.
using System.Xml.Linq; using System.Linq; public static class IEnumerableExtensions { public static string ToXml< T>(this IEnumerable< T> source, string rootTag = "List", string itemTag = "Item") { return new XElement(rootTag, source.Select(item => new XElement(itemTag, item))).ToString(); } }
Console.WriteLine(MyList.ToXml("Choices", "Channel"));