Tutorial :Query simple XDocument in LINQ


I'm probably doing something realy stupid but I cant get this to work:

var xmlQuery = from i in doc.Descendants("Item")    select new TriggerItem()    {    CreatedDate = DateTime.Now,    ItemIdentifier = i.Attribute("itemCode").Value,    Name = i.Attribute("name").Value,    ProductIdentifier = (i.Attribute("productCode") != null) ? i.Attribute("productCode").Value : null    };  

doc is an Xdocument object, which when debugging, i can confirm it has loaded the following xml:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>  <Items xmlns="http://mywebsite">  <Item itemCode="12345" productCode="" name="testing" categoryId="">  </Item>  </Items>  

so xmlQuery.Count() shud return 1, as one Item in ther, but it keeps returning 0!

iv also tried:

xmlQuery = from i in doc.Descendants("Items")   


xmlQuery = from i in doc.Descendants("Item")  

Even without creating a new TriggerItem object, it won't return anything ...any ideas?? :'(


I know XML so I can tell you that the Item element is in the "http://activepromotion.net/Data/TriggerItems/1.0" namespace, but you're searching for it in the default namespace.

I don't know LINQ to XML well enough to tell you how to do that, though.


You need to specify the namespace, something like....

XNamespace ns = XNamespace.Get("yourURI");  var qry = from i in doc.Descendants(ns + "Items")....  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »