tags:

views:

35

answers:

1

Hi,

i have a xml file which has following elements:

<rs:data>
<z:row entry='*[email protected]' type='1'/>

i need to access them by using Linq2Xml. My problem is that i get an exception which tells me that the ':' sign can not be used in Names.

my Linq2Xml Query is:

var rowQuery = from Mail in whiteMails.Descendants("xml").Descendants("rs:data").Descendants("z:row")
                       select Mail;

How can i handle this?

+1  A: 

rs:data is a name of an element which belongs to a namespace. The "rs" is a namespace prefix, the "data" is a local name. According to your comment above the rs prefix is declared for a namespace URI "urn:schemas-microsoft-com:rowset". This means that your element is identified as an element with local-name "data" and namespace URI "urn:schemas-microsoft-com:rowset". In LINQ to XML, all names need to be fully qualified by their namespace (it's also how XML works in general). In the code this is done by usage of XNamespace and XName classes. So for example:

XNamespace rsNamespace = XNamespace.Get("urn:schemas-microsoft-com:rowset");
XNamespace zNamespace = XNamespace.Get("#RowsetSchema");
var rowQuery = from Mail in whiteMails.Elements("xml")
                                      .Elements(rsNamespace + "data")
                                      .Elements(zNamespace + "row")
               select Mail;

Note that I've used Elements instead of Descendants. (Descendants would work as well). Descendants will return you all the element of the specified name in the entire subtree of the element you call it on - in any depth. Elements will return just all immediate children with that name. From your XML and query it seems you want the immediate children. Also Elements is much faster than Descendants since it only needs to go over the immediate children, not the entire subtree.

Vitek Karas MSFT
wow, very very nice description :) :) thank you very much, it works
darkdog