How to create an XML document using XDocument and XElement?
XDocument is a class used to build and represent an XML document. XElement is a class used to build an element object of an XML document. See the code example below:
using System;
using System.Collection.Generic;
using System.Xml.Linq;
namespace Build_Xml
{
public class Student
{
public string name {get; set;}
public string Id {get; set;}
}
public class Engine
{
static void main()
{
List<Student> students = CreateStudentList();
var studentXml = new XDocument();
var rootElem = new XEleemnt(“Students”);
studentXml.Add(rootElem);
foreach(Student student in students)
{
// Create an element for the Student object
var studentElem = new XElement(“Student”);
//Add element for name
var nameElem = new XElement(“Name”);
studentElem.Add(nameElem);
//Add element for Id
var IdElem = new XElement(“Id”);
studentElem.Add(IdElem);
//Now, add the Student object you just created to the root
rootElem.Add(studentElem);
}
Console.WriteLine(studentXml.ToString());
Console.Read();
}
private static List<Student> CreateStudentList()
{
new Student {name=”Elena”,Id=”405”},
new Student {name=”John”,Id=”406”}
};
Return students;
}
}
The code above will output the following XML document:
<Students>
<Student>
<name>Elena</name>
<Id>405</Id>
</Student>
<Student>
<name>John</name>
<Id>406</Id>
</Student>
</Students>
Silverlight DOM Parser
Parents of Child Elements
XML document using LINQ
XML document using XDocument and XElement?
Attributes and XAttribute
Read XML using XPathDocument
Search XML using LINQ
Serialize and deserialize XML
Empty XML element
Advantage of XmlReader and XmlWriter
Well formed XML VS Valid XML
XHTML VS HTML
Define XML
More Interview Questions.....