Search code examples
asp.netxmlvb.netdatatableplaylist

How to write a Column of a Datatable to XML with few tweaks?


I have a on memory Datatable like this.

datatable

I want to produce xml file like this.

xml

The URL (e.g. http:\www.mymusicwebsite.com\songs) will always be the same. Could anyone teach me how do I achieve this ?

Thanks A Lot.

L


Solution

  • Using LINQ-to-XML:

    // test items set, you need change to the column accessor
    // like dataTable.Rows[2] or dataTable.Rows["fileName"]
    // or row.Field<string>("filename") as noted by Mentoliptus
    IList<string> items = new List<string> { "song1.mp3", "song2.mp3", "song3.mp3" };
    
    XmlWriterSettings xws = new XmlWriterSettings();
    xws.OmitXmlDeclaration = true;
    xws.Indent = true;
    
    // You can output to file or even in a string
    using (var stream = File.Create(@"C:\test.xml"))
    using (XmlWriter xw = XmlWriter.Create(stream, xws))
    {                
        var xml = new XElement("smil",
            new XElement("body",
                new XElement("seq",
                    items.Select(c => new XElement("media", 
                                       new XAttribute(
                                           "src",
                                           String.Format("http:\\\\www..mysite.com\\songs\\{0}", c)))))));
    
        xml.Save(xw);
    }
    

    Output:

    <smil>
      <body>
        <seq>
          <media src="http:\\www..mysite.com\songs\song1.mp3" />
          <media src="http:\\www..mysite.com\songs\song2.mp3" />
          <media src="http:\\www..mysite.com\songs\song3.mp3" />
        </seq>
      </body>
    </smil>