Monday 29 July 2013

.Net Tips : Get the root element and root element name of a XML document using LINQ with C#.Net and VB.Net example

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 :

3 comments:

  1. not only tips now onwards write articles..jayeshsorathia,

    plz increase the tips then last year.

    response for my comment.

    ReplyDelete
  2. This is just a line of code but what I used was more than this, actually I used XDocument.Root to get the root element of a document.

    ReplyDelete
    Replies
    1. Hi,
      Thanks for your valuable comment. "XDocument.Root" return Root XElement object and there are many properties and methods of that object. You can use any of that.

      Delete