C# tutorial- create xml file with linq

Creating xml file with linq

Today XML is generally used to store data and transport it on the web. In this post, you learn how to create an Xml file by using Linq.

In the example code below, data source is a collection of few books stored in an array called Book. This data source will be used to create an XML file. To create objects of book, you will need a Book class. The Book class contains title, author, and published year. Below is the content of the Book class.

class Book
public string title;
public string author;
public int year;
public Book(string title, string author, int year)
this.title = title;
this.author = author;
this.year = year;

An XML file contains a root tag. In the root tag, you can define many child elements. Each element can have many attributes. Here is an example of an XML file.

create xml file with linq

You will use the XElement class to create an object that represents an element of the root. With the XElement class you can specify tag name, its attributes and sub-elements. An attribute of the element can be defined by using the XAttribute class. These classes are in the System.Xml.Linq namespace. Here is the C# code to generate an XML file called books.xml ( shown above) from the array of books.

Book[] books = new Book[] { new Book("Linq", "Dara", 2006), new Book("C# linq", "Dara", 2004), new Book("Java", "Dara", 2006) };
IEnumerable<XElement> xml = from book in books
select new XElement("Book", new XAttribute("title", book.title), new XElement("author", book.author), new XElement("year", book.year)); //read book data from the data source and construct xml elements
XElement Xml = new XElement("Books", xml); //create xml document
Xml.Save("d:/books.xml"); //save the data to xml file

The query syntax of Linq is similar to the SQL syntax. This syntax is used to retrieve elements of the data source. The result will be stored in the IEnumerable collection. In the example code above, each book is read from the books array by using the Linq's query syntax shown below. The book data such as title, author, and year are used to construct an XML element. The xml document constructed from the data source is stored in the xml IEnumerable collection. This collection can be written to a file by calling the Save method of the XElement class.






This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.