Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
8  
Please post the code you have written so far. People generally do not like to just write your code for you. – Mitch Wheat Jun 1 '10 at 8:33
5  
Agreed - this is actually extremely simple to do in a single statement, but just giving you the answer won't help you learn much. – Jon Skeet Jun 1 '10 at 8:37

1 Answer

up vote 58 down vote accepted

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.

share|improve this answer
5  
@ Jon Skeet: Thank you.... :-) – Anonymous Jun 1 '10 at 8:53
4  
Note: If you have elements that need to have "inner text" you add them like so: new XElement("description","this is the inner text of the description element."); (similar to how you add attribute/value pairs) – Myster Nov 23 '10 at 0:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.