Menu ▼

Previous Next

Reading XML using LINQ :

By using XDocument.Parse() method we can convert/read xml string to XDocumnet in LINQ. and we can set the xml to gridview as a result set. i.e. we can select the required columns and can assign it to a gridview.

Example :

Design :

<div>

    <asp:GridView ID="gvXML" runat="server" GridLines="Both" CellPadding="5">

    </asp:GridView>

</div>


Code Behind (C#) :

XDocument xdoc = XDocument.Parse(@"

                <Employees>

                    <Employee>

                        <Name>Thomas</Name>

                        <Designation>Executive</Designation>

                        <Department>Accounts</Department>

                        <Salary>5000</Salary>

                    </Employee>

                    <Employee>

                        <Name>Wills</Name>

                        <Designation>Manager</Designation>

                        <Department>Accounts</Department>

                        <Salary>24000</Salary>

                    </Employee>

                    <Employee>

                        <Name>Brod</Name>

                        <Designation>Manager</Designation>

                        <Department>Finance</Department>

                        <Salary>28000</Salary>

                    </Employee>

                    <Employee>

                        <Name>Smith</Name>

                        <Designation>Analyst</Designation>

                        <Department>Finance</Department>

                        <Salary>21000</Salary>

                    </Employee>

                </Employees>

                ");

var res = from emp in xdoc.Root.Elements()

            select new

            {

                EmployeeName = emp.Element("Name").Value,

                Department = emp.Element("Department").Value,

                Salary = emp.Element("Salary").Value

            };

gvXML.DataSource = res;

gvXML.DataBind();

 


Output :
EmployeeNameDepartmentSalary
ThomasAccounts5000
WillsAccounts24000
BrodFinance28000
SmithFinance21000
Previous Next




Search dotnetlearners.com