tags:

views:

889

answers:

1

i've a list (List< string>) "sampleList" which contains

Data1
Data2
Data3...

How to create an XML file using XDocument by iterating the items in the list in c sharp.

The file structure is like

<file>
   <name filename="sample"/>
   <date modified ="  "/>
   <info>
     <data value="Data1"/> 
     <data value="Data2"/>
     <data value="Data3"/>
   </info>
</file>

Now i'm Using XmlDocument to do this

Example

        List<string> lst;
        XmlDocument XD = new XmlDocument();
        XmlElement root = XD.CreateElement("file");
        XmlElement nm = XD.CreateElement("name");
        nm.SetAttribute("filename", "Sample");
        root.AppendChild(nm);
        XmlElement date = XD.CreateElement("date");
        date.SetAttribute("modified", DateTime.Now.ToString());
        root.AppendChild(date);
        XmlElement info = XD.CreateElement("info");
        for (int i = 0; i < lst.Count; i++) 
        {
            XmlElement da = XD.CreateElement("data");
            da.SetAttribute("value",lst[i]);
            info.AppendChild(da);
        }
        root.AppendChild(info);
        XD.AppendChild(root);
        XD.Save("Sample.xml");

please help me to do this

+7  A: 

LINQ to XML allows this to be much simpler, through three features:

  • You can construct an object without knowing the document it's part of
  • You can construct an object and provide the children as arguments
  • If an argument is iterable, it will be iterated over

So here you can just do:

List<string> list = ...;

XDocument doc =
  new XDocument(
    new XElement("file",
      new XElement("name", new XAttribute("filename", "sample")),
      new XElement("date", new XAttribute("modified", DateTime.Now)),
      new XElement("info",
        list.Select(x => new XElement("data", new XAttribute("value", x)))
      )
    )
  );

I've used this code layout deliberately to make the code itself reflect the structure of the document.

Jon Skeet
@ Jon Skeet: Thank you.... :-)
Pramodh