Creating an XML file from an IList

1.4k Views Asked by At

I have an IList to work with.

Can I loop through the rows in the list and create an XML file from this? If so how would I go about doing it?

I have been trying to get to grips with XDocument but I fail to see how I can loop through the IList using this method.

3

There are 3 best solutions below

3
On

If you're just after a fairly simple structure from a list of strings then this will work:

var list = new List<string> { "Joe", "Jim", "John" };

var document = new XDocument();
var root = new XElement("Root");
document.Add(root);
list.ForEach(x => root.Add(new XElement("Name", x)));
0
On

If you want to KISS, add System.Xml.Serialization to you project's References and:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;

public class Program {
    static void Main() {
        List<string> Data=new List<string> { "A","B","C","D","E" };

        XmlSerializer XMLs=new XmlSerializer(Data.GetType());
        XMLs.Serialize(Console.Out,Data);

        Console.ReadKey(true);
    }
}

I used Console.Out to give you a quick one-liney example, but you can pick any Stream, most likely a file to write to.

3
On

In two lines:

IList<string> list  = new List<string> {"A", "B", "C"};
var doc = new XDocument(new XElement("Root", list.Select(x => new XElement("Child", x))));

do not forget usings:

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

If the original IList is a non-generic IList, you will need to include a call to Enumerable.Cast<T>() so that the Select() can work. E.g.:

IList list  = new List<string> {"A", "B", "C"};
var doc = new XDocument(new XElement("Root",
    list.Cast<string>().Select(x => new XElement("Child", x))));