Error showing in Linq to xml [Resolved]

Posted by Klbaiju under LINQ on 12/13/2015 | Points: 10 | Views : 388 | Status : [Member] | Replies : 1
Hi,

I want to read and display an xml in Gridview

This is my XML file

<?xml version="1.0" encoding="utf-8"?>
<TourDetails>
<Tour
PCode="DEL"
TransCode="TSC1000"
Name="Transfer Delhi to Agra enroute Mathura"
From="Delhi"
Vehicle="Large Coach AC"
Rate="15000" />
<Tour
PCode="DEL"
TransCode="TSC1000"
Name="Transfer Delhi to Agra enroute Mathura"
From="Delhi"
Vehicle="Large Coach NAC"
Rate="10000" />
<Tour
PCode="DEL"
TransCode="TSC1000"
Name="Transfer Delhi to Agra enroute Mathura"
From="Delhi"
Vehicle="Ambassador AC"
Rate="8000" />
</TourDetails>

and i have tried following code

XDocument xmlDoc;

xmlDoc = XDocument.Load(Server.MapPath("Tour.xml"));
var fee = from p in xmlDoc.Descendants("TourDetails")

select new
{

Pcode = p.Element("PCode").Value,
TransCode = p.Element("TransCode").Value,
Name = p.Element("Name").Value,
};

GridView1.DataSource = fee;
GridView1.DataBind();

It showing error

Object reference not set to an instance of an object.

How to solve this

Regards

Baiju




Responses

Posted by: Rajnilari2015 on: 12/14/2015 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
Try

var fee =
(from p in doc.Root.Descendants()
select new
{
Pcode = p.Attribute("PCode").Value,
TransCode = p.Attribute("TransCode").Value,
Name = p.Attribute("Name").Value
}).ToList();


Lambda way

 var fee= doc.Root.Descendants().Select(p => new
{
Pcode = p.Attribute("PCode").Value,
TransCode = p.Attribute("TransCode").Value,
Name = p.Attribute("Name").Value
}).ToList();


--
Thanks & Regards,
RNA Team

Klbaiju, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response