简体   繁体   English

根据条件LINQ TO XML C#选择元素

[英]Select elements based on condition LINQ TO XML C#

I am querying XML using LINQ TO XML. 我正在使用LINQ TO XML查询XML。 I want to query records based on some conditional check here is my XML below: XML will have multiple Orders each order will be in I want to select order which has param node attribute store value is not null and if exists should be 1 and also order with carton information... 我想基于一些条件检查来查询记录,这是我的XML:XML将有多个Orders每个订单都在我要选择的订单中,其param节点属性存储值不为null,如果存在,则应为1,并且也为order带有纸箱信息...

    <orders>
        <order>
            <criteria>
                <param name="location">123</param>
                <param name="name">Chicago</param>
                <param name="Store">1</param>
                <param name="Account Number">1212121212</param>
            </criteria>
            <items>
                <item> </item>
                <item> </item>           
            </items>
            <cartons>
                <carton>
                     <size> </size>
                     <weight></weight>
                </carton>
            </cartons>
        </order>
    <Order>
    </Order>
    </orders>

I am able to do till this: 我可以做到这一点:

var result = from item in doc.Descendants("order")
                where item.Element("criteria").Element("param").Attribute("name").Value.Contains("store") == true
                && item.Element("cartons") != null
                select item;"

Above works fine if my store (param) attribute is first in the filter node but if I move the store(param) to other position than first it does not filter it 如果我的store(param)属性在过滤器节点中的第一个位置,则上述方法效果很好,但是如果我将store(param)属性移动到除第一个位置以外的其他位置,则它不会对其进行过滤

The problem is that you're only looking at one param element - always the first one, because that's what the Element does. 问题在于您仅查看一个 param元素-始终是第一个param元素,因为这就是Element所做的。

You want to match if any of the parameters is a "Store" element with a value of 1, so you want to use the Any method and use Elements to find all the parameters: 如果要匹配的任何参数是值为1的“ Store”元素,则要使用Any方法并使用Elements查找所有参数:

var query = from item in doc.Descendants("order")
            where item.Element("criteria").Elements("param")
                      .Any(p => p.Attribute("name").Value == "Store" &&
                                (int) p == 1)
                  && item.Element("cartons") != null
            select item;

The query expression isn't really helping you here - I'd use: 查询表达式在这里并没有真正帮助您-我会使用:

var query = doc.Descendants("order")
               .Where(item => item.Element("criteria").Elements("param")
                                  .Any(p => p.Attribute("name").Value == "Store" &&
                                            (int) p == 1)
                              && item.Element("cartons") != null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM