Creating XML

Apart from querying XML, we can also use LINQ to create XML files. To do this, we can use the XElement class. There is an ADD method available in the class that we can use to construct an XML file. The following code syntax shows how we can create some XML:

XElement root = new XElement("Student",
new List<XElement>
{
new XElement("Marks"),
new XElement("Attendance")
},
new XAttribute("Roll Number", 1));
root.Save("StudentTestResults.xml");

In the preceding code, we have defined an element by the name Student. In the root element, we have added a child node of Marks to represent the marks the student has earned. We have also added a child node of Attendance to represent the attendance of Student. Finally, we have added a "Roll Number" attribute to represent the unique identifier of Student

Once the code is executed, we will observe that it has created an XML file with the following structure:

<?xml version="1.0" encoding="utf-8"?>
<Student RollNumber="1">
<Marks />
<Attendance />
</Student>

In the next section, we will look at how we can use LINQ to update XML. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.202.203