开发者

C# XML Dynamic LINQ

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 q开发者_如何转开发uery. I have not found example in internet with xml query.

Thx for any response! D.


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!


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜