Querying XML Data With Namespace In C#

Introduction

Generally, we use LINQ to XML while reading data from XML. LINQ to XML works perfectly with XML normal data without namespace. But sometime we get XML data with namespace and in that scenario it won’t work perfectly. In order to resolve problem, we need to create XNamespace object and bind it LINQ to XML. Let’s see how we can achieve.

The following is the XML data from where we will read data. In below XML data you will find namespace is used (xmlns).
  1. <?xml version="1.0" encoding="iso-8859-1"?>  
  2. <league xmlns="http://feed.elasticstats.com/schema/basketball/schedule-v2.0.xsd">  
  3.     <daily-schedule date="2014-04-13">  
  4.         <games>  
  5.             <game id="53a41428-d8f7-4020-97cc-13792e6994eb" status="closed" scheduled="1">  
  6.                 <venue name="Bankers Life Fieldhouse"/>  
  7.                 <home name="Indiana Pacers" alias="IND">  
  8.                 </home>
  9.                 <away name="Oklahoma City Thunder">  
  10.                 </away>  
  11.             </game>  
  12.         </games>  
  13.     </daily-schedule>  
  14. </league>  
Here are the steps to read XML data when XML contains namespace tag.

Step 1: Declare XNamespace object and assign namespace value to object.
  1. XDocument xdoc = XDocument.Load(Server.MapPath("Daily_schedule.xml"));  
  2. XNamespace ns = "http://feed.elasticstats.com/schema/basketball/schedule-v2.0.xsd";  
Step 2: Add XNamespace object to LINQ to XML.
  1. var gameList = (from rec in xdoc.Descendants(ns + "game")  
  2.    where (string)rec.Attribute("id") == "53a41428-d8f7-4020-97cc-13792e6994eb"  
  3.    select new  
  4.    {  
  5.       id = rec.Attribute("id").Value,  
  6.       venue = rec.Element(ns + "venue").Attribute("name").Value,  
  7.       home = rec.Element(ns + "home").Attribute("name").Value,  
  8.       away = rec.Element(ns + "away").Attribute("name").Value,  
  9.       status = rec.Attribute("status").Value,  
  10.       scheduled = rec.Attribute("scheduled").Value  
  11. }).ToList();  
Step 3: Loop over list(gameList) to get the actual result.
  1. foreach (var p in gameList)  
  2. {  
  3.    // Append your other properties  
  4.    Response.Write(p.id + p.status); 
  5. }  
Output
 
 
Figure 1: Getting value from XML  

Hope this blog helps you to read data from XML when it contains Namespace.