Reading XML data using C#.NET Linq
Posted on 2008-09-29
What is the easiest way to read through an XML document to get the values of each element in C#.NET? I am trying to use Linq but when i try to loop through each record i get a "Object reference not set to an instance of an object." error.
The document is an Order Request which may include several orders and each order has different BillTo, ShipTo, Line Item etc. sections.
The basic code I am using looks like this:
String xmlFile = @"D:\TestOrder.XML";
XDocument xDoc = XDocument.Load(xmlFile, LoadOptions.SetLineInfo);
var order = from orderRequest in xDoc.Descendants("OrderRequest")
BillToCity = (string)orderRequest.Element("City").Value,
foreach (var orderRequest in order) // This is where the error occurs
xmlTest = orderRequest.BillToCity;
Any tips would be greatly appreciated. If there is an easier/quicker way to read through an XML file than using Linq that would help as well.