Showing posts with label LinqToXML. Show all posts
Showing posts with label LinqToXML. Show all posts

Friday, 20 December 2013

You can validate the data of XML file and identify XML elements which are failed to validate. We can easily achieve this using LINQ.

Here is example for this.
In this example we take one 'customer.xml' file. In this file we have 'name' and 'phone' element. We need to validate phone number with REGEX and display it's validate result either it is true or false.

Wednesday, 11 December 2013

Using LINQ you can check that attribute exist in element or not. There is property called "HasAttributes" of XElement class to check existence of attribute.

Here is example for this.

In this example we take one 'customers.xml' file which contains customers information like name, id, etc. Now we check that does "customer" element has 'id' attribute or not. In XML there is one customer 'David' which does not have 'id' attribute. Now we iterate each 'customer' element and display that it element has attribute or not.

Wednesday, 20 November 2013


 XML file contains various types of data like string, integer, date, etc. Now if we want to get data from XML file order by some attribute which contains dates at that time we need to do some special things if we are not doing that at that time data is not sorted date wise it will treat as normal string sorting. We can do date wise sorting. 

Here are examples for this.
In this example we are taking on 'Books.xml' file which contains books details in this XML file for each book element we are one "ReleaseDate" element which contains date value. Now we take that XML file in XMLDocument object and sort on "ReleaseDate" attribute by converting that string date into date datatype.

Wednesday, 16 October 2013

You can query objects using SelectMany LINQ method and get result according to your given criteria. You can also query more than one criteria.

Here is example for this.

In this example we take "books.xml". Now we query on element "author" whose sub element is 'firstname' and 'lastname' and we only want list of authors whose name is either 'Pratik' or 'David'.

Thursday, 26 September 2013

We can get or retrieve full path of the given XML Node or Element. Means from root element to the given XML Node. We can achieve this  LINQ's extensions methods. We are using 'Descendants', 'AncestorsAndSelf' and 'Reverse' methods.

  • Descendants : Returns filtered collections of the given elements from document or element. For more details Click Here.
  • AncestorsAndSelf : Returns collection of elements that contain this element. For more details Click Here.

Here is C#.Net example and VB.Net example.

Wednesday, 11 September 2013

You can directly get element of particular position or query that element using LINQ's 'Descendants' and 'ElementAt' method.

  • 'Descendants' is a method of XDocument class which accept name of element as string.
  • 'ElementAt' is a method of 'XElement' class which accept integer value of index.

Means you can query the 2nd book element in the XML document or file. You can also call that as positional predicate.

Here is example for this.
In this example we took one XML file 'BooksList.xml'. Now we use 'Descendants' method of 'XDocument' and pass 'book' element and after that, we use 'ElementAt' method and pass '1' so that we can get 2nd element of 'book' from that XML file.


C#. Net Example :
XDocument objDoc = XDocument.Load(Server.MapPath("BooksList.xml"));
XElement objElement = objDoc.Descendants("book").ElementAt(1);

Response.Write("<b>Title Element Value : </b>" + objElement.Element("Title").Value);
Response.Write("<br/>");
Response.Write("<b>ReleaseDate Element Value : </b>" + objElement.Element("ReleaseDate").Value);
Response.Write("<br/>");
Response.Write("<b>Pages Element Value : </b>" + objElement.Element("Pages").Value);

VB.Net Examples :
Dim objDoc As XDocument = XDocument.Load(Server.MapPath("BooksList.xml"))
Dim objElement As XElement = objDoc.Descendants("book").ElementAt(1)

Response.Write("<b>Title Element Value : </b>" + objElement.Element("Title").Value)
Response.Write("<br/>")
Response.Write("<b>ReleaseDate Element Value : </b>" + objElement.Element("ReleaseDate").Value)
Response.Write("<br/>")
Response.Write("<b>Pages Element Value : </b>" + objElement.Element("Pages").Value)

BooksList.xml
<?xml version="1.0" encoding="utf-16"?>
<books>
  <book ISBN="asp1">
    <Title>ASP.NET</Title>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
  </book>
  <book ISBN="c#2">
    <Title>C#.NET</Title>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
  </book>
</books>


Output :
LINQ positional predicate


Below are the books that you would like :

Monday, 26 August 2013

You can get Parent element from child element using LINQ method. Some times there are situations when you traverse XML file and you reach at child node and you want to get details of Parent node at that time you can use "Parent" method which will give you parent node as XElement object.

Here is example for this.
In this example we took one "BooksList.xml" file. Now we traverse to child node "Title" and after that, we get its parent node using "Parent" property.

Monday, 29 July 2013

There are situations where some time we want to get root element of XML file or document. We can get this root element and root element name very easily. We are using "Root" property of "XDocument" class.

Here is example for this.
In this example we take on "BooksList.xml" file and we display its root element name.

C#. Net Example :
        XElement objRootElement = XDocument.Load(Server.MapPath("BooksList.xml")).Root;
        Response.Write("<b>Name of root element is : </b>" + objRootElement.Name);

VB.Net Examples :
        Dim objRootElement As XElement = XDocument.Load(Server.MapPath("BooksList.xml")).Root
        Response.Write("<b>Name of root element is : </b>" & objRootElement.Name.ToString())

Output :


Below are the books that you would like :

Monday, 15 July 2013

We can get specific attributes values from XML file or document or object using LINQ. We are using "Elements" and "Attributes" methods of XML document object to get attributes values.

Here is example for this.
In this example we take one "BooksList.xml" file. This file contains books related details and each book has ISBN number which appears as attribute in "<book>" node. We retrieve this attribute using LINQ and display on screen.

Thursday, 5 July 2012

XDocument is Introduce in System.Xml.Linq namespace.
XDocument is more friendlier and easy to use than XMLDocument.
Earlier we are using XMLDocument for read and processing XML File.
Syntax of retrieving element from XML document is different than XMLDocument.
Every .Net Beginners needs to know this. 

Here is example for this.
In this example We load Books.xml file and read data from this file using LINQ to XML and display in grid as well as display count of books.

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Books>
   <Book>
    <Title>ASP.NET</Title>
    <ISBN>asp1</ISBN>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>C#.NET</Title>
    <ISBN>c#2</ISBN>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>VB.NET</Title>
    <ISBN>vb3</ISBN>
    <ReleaseDate>5/5/2009</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>SQL Server</Title>
    <ISBN>sql4</ISBN>
    <ReleaseDate>6/9/2010</ReleaseDate>
    <Pages>300</Pages>
    <PublisherId>2</PublisherId>
  </Book>
  <Book>
    <Title>JAVA</Title>
    <ISBN>java5</ISBN>
    <ReleaseDate>8/5/2011</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>3</PublisherId>
  </Book>
</Books>


ASPX Code :
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvBooks" runat="server">
        </asp:GridView>
    </div>
</form>

C# Example :
        XDocument objBooksXML = XDocument.Load(Server.MapPath("books.xml"));
        var objBooks = from book in
                       objBooksXML.Descendants("Book")
                       select new { 
                                    Title = book.Element("Title").Value, 
                                    Pages = book.Element("Pages").Value 
                                  };

        Response.Write(String.Format("Total {0} books.", objBooks.Count()));
        gvBooks.DataSource = objBooks;
        gvBooks.DataBind();

VB.net Example :
        Dim objBooksXML As XDocument = XDocument.Load(Server.MapPath("books.xml"))
        Dim objBooks = From book In objBooksXML...<Book>
                       Select New With {.Title = book.<Title>.Value, .Pages = book.<Pages>.Value}
        Response.Write(String.Format("Total {0} books.", objBooks.Count()))
        gvBooks.DataSource = objBooks
        gvBooks.DataBind()

Output : 


Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that. 


Monday, 4 June 2012

Using LINQ to XML you can also join multiple files and get result based on LINQ query.
LINQ to XML uses System.Xml.Linq namespace.

Here are example for this.

In this examples we have to XML files first "Books.xml" and second "Publishers.xml",
we are joining this two files with one common field "PublisherId". We are fetching "PublisherName" from "Publishers.xml" file to display in grid.

Here are examples :

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Books>
   <Book>
    <Title>ASP.NET</Title>
    <ISBN>asp1</ISBN>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>C#.NET</Title>
    <ISBN>c#2</ISBN>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>VB.NET</Title>
    <ISBN>vb3</ISBN>
    <ReleaseDate>5/5/2009</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>SQL Server</Title>
    <ISBN>sql4</ISBN>
    <ReleaseDate>6/9/2010</ReleaseDate>
    <Pages>300</Pages>
    <PublisherId>2</PublisherId>
  </Book>
  <Book>
    <Title>JAVA</Title>
    <ISBN>java5</ISBN>
    <ReleaseDate>8/5/2011</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>3</PublisherId>
  </Book>
</Books>

XML File : (Publishers.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Publishers>
  <Publisher>
    <PublisherId>1</PublisherId>
    <PublisherName>Microsoft</PublisherName>
  </Publisher>
  <Publisher>
    <PublisherId>2</PublisherId>
    <PublisherName>Wrox</PublisherName>
  </Publisher>
  <Publisher>
    <PublisherId>3</PublisherId>
    <PublisherName>Sun Publications</PublisherName>
  </Publisher>
</Publishers>

ASPX Code :
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvBooks" runat="server">
        </asp:GridView>
    </div>
</form>

C# Example :
    protected void Page_Load(object sender, EventArgs e)
    {
        var query = from bl in
                    XElement.Load(MapPath("Books.xml")).Elements("Book")
                    join g in XElement.Load(MapPath("Publishers.xml")).Elements("Publisher")
                    on (int)bl.Element("PublisherId") equals (int)g.Element("PublisherId")
                    select new 
                    {
                        Title = (string)bl.Element("Title"),
                        ISBN = (string)bl.Element("ISBN"),
                        ReleaseDate = (DateTime)bl.Element("ReleaseDate"),
                        Pages = (int)bl.Element("Pages"),
                        PublisherName = (string)g.Element("PublisherName")
                    };

        gvBooks.DataSource = query;
        gvBooks.DataBind();
    }

VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim query = From bl In XElement.Load(MapPath("Books.xml")).Elements("Book") _
                    Join g In XElement.Load(MapPath("Publishers.xml")).Elements("Publisher") _
                    On CInt(bl.Element("PublisherId")) Equals CInt(g.Element("PublisherId")) _
                    Select New With { _
                        .Title = CStr(bl.Element("Title")), _
                        .ISBN = CStr(bl.Element("ISBN")), _
                        .ReleaseDate = CDate(bl.Element("ReleaseDate")), _
                        .Pages = CInt(bl.Element("Pages")), _
                        .PublisherName = CStr(g.Element("PublisherName")) _
                    }
        gvBooks.DataSource = query
        gvBooks.DataBind()
    End Sub

Output :

Wednesday, 30 May 2012

Using LINQ to XML we can use the same basic LINQ syntax to query XML documents.
LINQ to XML uses System.Xml.Linq namespace.
Here are example for this.
In this example we have Books.xml file which contains books details. Now we query this xml files and display it's data in grid using LINQ .
In LINQ to XML we have to provide mapping logic in LINQ query.

Here are examples :

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
<Books>
   <Book>
    <Title>ASP.NET</Title>
    <ISBN>asp1</ISBN>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>C#.NET</Title>
    <ISBN>c#2</ISBN>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>VB.NET</Title>
    <ISBN>vb3</ISBN>
    <ReleaseDate>5/5/2009</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>1</PublisherId>
  </Book>
  <Book>
    <Title>SQL Server</Title>
    <ISBN>sql4</ISBN>
    <ReleaseDate>6/9/2010</ReleaseDate>
    <Pages>300</Pages>
    <PublisherId>2</PublisherId>
  </Book>
  <Book>
    <Title>JAVA</Title>
    <ISBN>java5</ISBN>
    <ReleaseDate>8/5/2011</ReleaseDate>
    <Pages>400</Pages>
    <PublisherId>3</PublisherId>
  </Book>
</Books>

ASPX Code :
<form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvBooks" runat="server">
        </asp:GridView>
    </div>
</form>

C# Example :
 public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        var query = from m in
                    XElement.Load(MapPath("Books.xml")).Elements("Book")
                    select new Books
                    {
                        Title = (string)m.Element("Title"),
                        ISBN = (string)m.Element("ISBN"),
                        ReleaseDate = (DateTime)m.Element("ReleaseDate"),
                        Pages = (int)m.Element("Pages"),
                        PublisherId = (int)m.Element("PublisherId")
                    };

        gvBooks.DataSource = query;
        gvBooks.DataBind();
    }

VB.net Example :
 Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim query = From m In XElement.Load(MapPath("Books.xml")).Elements("Book") _
                    Select New Books With { _
                        .Title = CStr(m.Element("Title")), _
                        .ISBN = CStr(m.Element("ISBN")), _
                        .ReleaseDate = CDate(m.Element("ReleaseDate")), _
                        .Pages = CInt(m.Element("Pages")), _
                        .PublisherId = CInt(m.Element("PublisherId")) _
                    }
        gvBooks.DataSource = query
        gvBooks.DataBind()
    End Sub

Output : 


For Beginning .Net articles. Click Here...

This type of .Net Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.