views:

32

answers:

2

Hi all, I am trying query an xml file with dinamyc linq query. I have followed the scottGu's Blog

scottGu's Blog

But I have a problem to make the where clause. This is the scenario.

<Rates>
<Rate id="1" tax="20.5" sex="M" name="Jhon">
<Rate id="2" tax="2.5" sex="F" name="Aline">
</Rate>

The idea is to query the xml using a filter with sex and name.

XDocument doc = XDocument.Load(new StringReader(xml));
var query = doc.Elements("Rates").Attributes().AsQueryable().Where("sex='M' and and name='Jhon'");

I use this method because with SelectSingleNode() method I have problem if the parameter in where clause are not ordered and because the query is dynamic.

But I have this error:
No property or field 'sex' exists in type 'XAttribute'

I don't know is syntax are correct, and if is the right way to make a dynamic query. I have not found example in internet with xml query.

Thx for any response! D.

A: 
XDocument doc = XDocument.Load(new StringReader(xml));
var query = from element in doc.Elements("Rates")
            Where element.Attribute("sex").Value.Equals('M') &&
                  element.Attribute("name").Value.Equals("John")
            select element;

That is how I would go about it. Seems a bit easier to read than yours and gives you the output that you are hoping for. Enjoy!

Adkins
Sorry misread your question. That is a basic Linq query not a dynamic one. As I don't have any experience with Dynamic Linq library I can't even really update my answer at all
Adkins
Thx! But the xml are not equals. The only thing equal is the document root "Rates" but the content (for content I mean xml attributes) changes for each xml. The attributes may be more or less, and name change. For this I must be able to use a dynamic query not coded in file..
hanc
A: 

Dynamic Linq doesn't work like that. The criteria you're using in the Where clause generates an expression similar to this:

... Where(attr => attr.sex == "M" && attr.name == "John")

sex and name are not properties of XAttribute, so it doesn't work.

Anyway, I don't think you can use Dynamic Linq to generate Linq to XML queries... It works for Linq to Objects, and also for Linq to SQL and Linq to Entities because the expression is transformed into SQL by the Linq provider, but there is no provider that generates Linq to XML queries...

Thomas Levesque