Welcome to MSDN Blogs Sign in | Join | Help

Wriju's BLOG

.NET and everything
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!!!

Posted: Thursday, May 29, 2008 9:23 PM by wriju

Comments

Philip said:

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.

# May 31, 2008 10:48 AM

Edilberto Sánchez Forero said:

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>

# December 1, 2008 3:27 PM

Nick said:

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?

# March 31, 2009 4:56 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker