LINQ to
XML
When
we interact with XML using LINQ then it is known as LINQ to XML.
To work with XML in LINQ you have to add a namespace
using System.Xml.Linq.
I am taking the following xml
file for an example:-
<?xml version=”1.0”
encoding=”utf-8” ?>
<Techaltum>
<student
Code=”101”>
<name>isha
malhotra</name>
<id>
1 </id>
<course>
asp.net </course>
</student>
<student
Code=”102”>
<name>Avi
malhotra</name>
<id>
2 </id>
<course>
Web Designing </course>
</student>
<student
Code=”103”>
<name>Neha</name>
<id>
3 </id>
<course>
Java </course>
</student>
</Techaltum>
If I consider this xml file then
in this file first line is declaration. Techaltum is an element and in student
element code is attribute.
First I will discuss how to
declare all these in LINQ.
Syntax
of Declaration in LINQ:-
XDeclaration dec = new XDeclaration("1.0", "utf-8",
"yes");
Syntax
of Element in LINQ:-
XElement student = new XElement("");
Syntax
of Attribute in LINQ:-
XAttribute code;
Syntax
of comment in LINQ:-
XComment comm = new XComment("");
Create
complete xml file using LINQ
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using
System.Web.UI.WebControls;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
XDocument
techaltum_doc = new XDocument(new XDeclaration("1.0", "utf-8",
"yes"),
new
XElement("Techaltum",
new XElement("student", new
XAttribute("code",
"101"),
new XElement("name", "Isha
Malhotra"), new XElement("id",
"1"), new
XElement("course",
"asp.net")),
new XElement("student", new
XAttribute("code",
"102"),
new XElement("name", "Avi
Malhotra"), new XElement("id",
"2"), new
XElement("course",
"web Desiging")),
new XElement("student", new
XAttribute("code",
"103"),
new XElement("name", "Neha"),
new XElement("id", "3"),
new XElement("course", "Java"))
)
);
//storage of file
techaltum_doc.Save(Server.MapPath("xml")+"/abc.xml");
}
}
To store this file I simply
created the folder name xml in my visual studio. After executing this code
refresh this folder and you will get your file in this folder.
Figure 1
Hope you enjoyed the article.
No comments:
Post a Comment