XML file creation Using XDocument in C#

Posted by Pramodh on Stack Overflow See other posts from Stack Overflow or by Pramodh
Published on 2010-06-01T08:31:37Z Indexed on 2010/06/01 8:53 UTC
Read the original article Hit count: 327

Filed under:
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml