How to read XML using LINQ - ASP.NET C#

LINQ -  stand for Language Integrated Query is powerful features that extend the query capability to the language syntax in C# or Visual basic.

In this tutorial, I will show one example of how to read XML file using Linq.

Checklist :
  1. Create one aspx page name "ReadxmlUsingLinq.aspx".
  2. Create one xml file name "XmlDataTest.xml"

The XmlDataTest.xml 

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <TransactionName Description="Transaksi ASB">
    <MENU Name="Inquiry">
      <ITEMS TargetUrl="/Transaction/Default.aspx" DESCRIPTION="DefaultPage" ShortcutKey="Ctrl + H,1"></ITEMS>
      <ITEMS TargetUrl="/Transaction2/Default.aspx" DESCRIPTION="DefaultPage2" ShortcutKey="Ctrl + H,2"></ITEMS>
      <ITEMS TargetUrl="/Transaction3/Default.aspx" DESCRIPTION="DefaultPage3" ShortcutKey="Ctrl + H,3"></ITEMS>
      <ITEMS TargetUrl="/Transaction4/Default.aspx" DESCRIPTION="DefaultPage4" ShortcutKey="Ctrl + H,4"></ITEMS>
    </MENU>
  </TransactionName>
</root>



The ReadxmlUsingLinq.aspx Page

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    CodeBehind="ReadxmlUsingLinq.aspx.cs" Inherits="BlogExample.ReadxmlUsingLinq" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">   
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</asp:Content>



The ReadxmlUsingLinq.aspx Code Behind

using System;
using System.Collections.Generic;
using System.Web;
using System.Linq;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace BlogExample
{
    public partial class ReadxmlUsingLinq : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string output = "";
                string path = Server.MapPath("~") + "/XML/XmlDataTest.xml";

                XDocument xDoc = XDocument.Load(path);
                var feed = from collection in xDoc.Descendants("MENU")
                           select new
                           {
                               UniqueID = collection.Elements("ITEMS")
                           };

                int feedItem = feed.ToList().Count;
                int countLength = 0;
                if (feedItem != 0)
                {
                    //this step to count how many length element to set in string array
                    foreach (var a in feed)
                    {
                        int countElement = a.UniqueID.Count();
                        countLength = countLength + countElement;
                    }
                }

                output += "The Unique ID count : " + countLength.ToString() + "<br/>";
               
                if (feedItem != 0)
                {
                   
                    int index = 1;
                    foreach (var a in feed)
                    {
                        int countElement = a.UniqueID.Count();
                        for (int k = 0; k < countElement; k++)
                        {
                            output += "Details number " + index.ToString() + "<br/>";
                            output += "The Target URL : " + a.UniqueID.ElementAt(k).Attribute("TargetUrl").ToString().Replace("TargetUrl=", "").Replace("\"","") + "<br/>";
                            output += "The DESCRIPTION : " + a.UniqueID.ElementAt(k).Attribute("DESCRIPTION").ToString().Replace("DESCRIPTION=", "").Replace("\"", "") + "<br/>";
                            output += "The ShortcutKey : " + a.UniqueID.ElementAt(k).Attribute("ShortcutKey").ToString().Replace("ShortcutKey=", "").Replace("\"", "") + "<br/>";
                            output += "<br/>";
                            index++;
                        }
                    }
                    Label1.Text = output;
                }
            }
        }
    }
}

The Output



References

  1. http://msdn.microsoft.com/en-us/library/vstudio/bb397926.aspx

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example