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).
- <?xml version="1.0" encoding="iso-8859-1"?>
- <league xmlns="http://feed.elasticstats.com/schema/basketball/schedule-v2.0.xsd">
- <daily-schedule date="2014-04-13">
- <games>
- <game id="53a41428-d8f7-4020-97cc-13792e6994eb" status="closed" scheduled="1">
- <venue name="Bankers Life Fieldhouse"/>
- <home name="Indiana Pacers" alias="IND">
- </home>
- <away name="Oklahoma City Thunder">
- </away>
- </game>
- </games>
- </daily-schedule>
- </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.
- XDocument xdoc = XDocument.Load(Server.MapPath("Daily_schedule.xml"));
- XNamespace ns = "http://feed.elasticstats.com/schema/basketball/schedule-v2.0.xsd";
Step 2: Add XNamespace object to LINQ to XML.
- var gameList = (from rec in xdoc.Descendants(ns + "game")
- where (string)rec.Attribute("id") == "53a41428-d8f7-4020-97cc-13792e6994eb"
- select new
- {
- id = rec.Attribute("id").Value,
- venue = rec.Element(ns + "venue").Attribute("name").Value,
- home = rec.Element(ns + "home").Attribute("name").Value,
- away = rec.Element(ns + "away").Attribute("name").Value,
- status = rec.Attribute("status").Value,
- scheduled = rec.Attribute("scheduled").Value
- }).ToList();
Step 3: Loop over list(gameList) to get the actual result.
- foreach (var p in gameList)
- {
-
- Response.Write(p.id + p.status);
- }
Output:
Figure 1: Getting value from XML
Hope this blog helps you to read data from XML when it contains Namespace.