LINQ to XML : Querying XML with Namespaces

This question arises in one of discussions. If you have a XML document with “xmlns” then LINQ to XML does not return any IEnumerable<T> J. This is strange but true for XPath and XQuery.

There is a trick to get it done,

Let us assume that you have a XML as follows,

<?xml version="1.0" encoding="utf-8"?>

<products xmlns="myns-com">

  <product ProductID="1" CategoryID="1">

    <ProductName>Chai</ProductName>

  </product>

  <product ProductID="2" CategoryID="1">

    <ProductName>Chang</ProductName>

  </product>

</products>

Now this code holds namespace and all the child element’s default namespace would be that one “myns-com”.

So if you try to write query against this XML

var query = from lst in XElement.Load(@"c:\NS.xml").Elements(“product")

            select (int)lst.Attribute("ProductID");

foreach (var k in query)

{

    Console.WriteLine(k);

}

This seems correct though it will not give you any output.

What you need to do is, you need to the namespace in the query,

XNamespace ns = "myns-com";

           

var query = from lst in XElement.Load(@"c:\NS.xml").Elements(ns+"product")

            select (int)lst.Attribute("ProductID");

foreach (var k in query)

{

    Console.WriteLine(k);

}

You will get the desired output as you may expect.

Namoskar!!!