Tuesday, January 7, 2014

Create New XML file using C#

I want to create xml file using c#. so i have to created like
XML File source file.
<Students>
    <Student>
      <Name>senthil</Name>
      <Subject1>50</Subject1>
      <Subject2>60</Subject2>
      <Subject3>70</Subject3>
      <Subject4>80</Subject4>
      <Image>
 <ImageOrigin>
  <X>1</X>
  <Y>10</Y>
 </ImageOrigin>

      </Image>
    </Student>
</Students>
Created xml using c# code.
XDocument document = new XDocument();
XElement rootElement = new XElement("Students");

foreach(Student student in StudentsCollection)
{
    XElement studentElement = new XElement("Student");
    
    studentElement.Add(new XElement("Name") { Value = student.Name });
    studentElement.Add(new XElement("Subject1") { Value = student.Subject1 });
    studentElement.Add(new XElement("Subject2") { Value = student.Subject2 });
    studentElement.Add(new XElement("Subject3") { Value = student.Subject3 });
    studentElement.Add(new XElement("Subject4") { Value = student.Subject4 });
    studentElement.Add(new XElement("Image"));

    XElement imageElement = studentElement.Element("Image");

    imageElement.Add(new XElement("ImageOrigin"));

    XElement imageOriginElement = imageElement.Element("ImageOrigin");

    imageOriginElement.Add(new XElement("X") { Value = "1" });
    imageOriginElement.Add(new XElement("Y") { Value = "10" });

    rootElement.Add(studentElement);
}

document.Add(rootElement);
document.Save("D:\Stduent.xml");

No comments:

Post a Comment