Search code examples
xmllinqnamespacesprefix

linq to xml with namespace prefix


I have the following xml

<Location xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Latitude>-1</Latitude>
<Longtitude>-1</Longtitude>
</Location>

And without the namespace (xmlns:i...), I could use the following the query

//xdoc is an XDocument loaded with the above xml
var locCollection = from p in xdoc.Descendants("Location") 

with namespace but without the prefix "i", I could use the following the query

XNamespace ns = @"http://www.w3.org/2001/XMLSchema-instance"
var locCollection = from p in xdoc.Descendants(ns + "Location")

So how do I deal with te "i" prefix?

Thanks.


Solution

  • The problem is that when you provide the namespace prefix, you need to explicitly prefix the XML elements that are in that namespace. So in your example, if you explicitly specify the prefix as in i:Location then your queries will work.

    <i:Location xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
      <Latitude>-1</Latitude> 
      <Longtitude>-1</Longtitude> 
    </i:Location> 
    

    The reason it worked without the prefix is because with out the prefix specified the namespace is considered the default namespace therefore Location was by default scoped to the namespace.