LINQ to XML : Querying XML with Namespaces

LINQ to XML : Querying XML with Namespaces

  • Comments 4

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!!!

Leave a Comment
  • Please add 8 and 6 and type the answer here:
  • Post
  • Very good suggestion. I know this is "expected behavior" by Microsoft, but it can still be irksome to encounter this problem. Thanks for the tip.

  • But what i must to do with something like:

    <listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema" xmlns="http://schemas.microsoft.com/sharepoint/soap/">

    <rs:data ItemCount="1">

    <z:row ows_ID="1" ows_ContentTypeId="0x010400E2AEC2E6B16C284B96E44115A7C4E923" ows_ContentType="Anuncio" ows_Title="Introducción a Windows SharePoint Services" ows_Modified="2008-12-01T19:33:10Z" />

    </rs:data>

    </listitems>

  • Hi, with this example, how would access for the ProductName be allowed, running through the code the ProductName element would need to be part of the namespace, yet in linq it considers it to be a value, so if you update the xml with a new element with the product element it will also consider it to be a value rather than an element, any ideas?

  • Thank you.  Short, sweet and to the point.

Page 1 of 1 (4 items)