3

这是我的 xml 文件:

<items>
  <item code="1">
    <info1>LOREM</info1>
    <info2>IPSUM</info2>
    <info3>DOLOR</info3>
  </item>
  <item code="2">
    <info1>LOREM</info1>
    <info2>AMET</info2>
    <info3>CONSECTETUER</info3>
  </item>
  <item code="3">
    <info1>LOREM</info1>
    <info2>IPSUM</info2>
    <info3>CONSECTETUER</info3>
  </item>
</items>

我想根据存储在该字典中的标准提取一些项目代码:

{ "info1", "LOREM" }
{ "info2", "IPSUM" }

我写了那个 linq 查询:

var test =  from element in xml.Descendants("item").Elements()
        from param in dicoParams
        where param.Key == element.Name.ToString() && param.Value == element.Value
        select element.Parent.Attribute("code");

但输出是:

code="1"
code="1"
code="2"
code="3"
code="3"

我所期望的是:

code="1"
code="3"

我们可以注意到查询返回的元素至少满足一个条件,但我希望它同时满足这两个条件。

我怎么能写那个查询?

4

3 回答 3

3

I think you expect 2 also, as 2 contains info1 which contains LOREM.

Regardless, I think this is what you are looking for:

var test =  from element in xml.Descendants("item")
    from param in dicoParams
    where element.Elements()
        .Any(e => e.Name.ToString() == param.Key && e.Value == param.Value)
    select element.Attribute("code");

This will output only one code regardless of the number of matches.

Actually, as @user1068352 mentions in the comments, it looks like you want items that match ALL items in the dictionary.

If that's the case, try this:

var test = from element in xml.Descendants("item")
    where dicoParams.All(d => element.Elements
        .Any(e => e.Name.ToString() == d.Key && e.Value == d.Value))
    select element.Attribute("code");
于 2013-06-05T10:37:53.683 回答
0
 var test1 = (from element in elem.Descendants().Elements()
                         from item in val
                         where item.Key == element.Name.ToString() && item.Value == element.Value
                         select element.Parent.Attribute("code")).GroupBy(t => t.Parent.Attribute("code"));

你也可以使用 group by

于 2013-06-05T11:03:39.320 回答
0

像这样的东西应该工作:

var test =
    from element in xml.Descendants("item")
    where element.Elements()
        .Any(x =>
            dicoParams.ContainsKey(x.Name.ToString())
            && dicoParams[x.Name.ToString()] == x.Value)
    select element.Attribute("code");

但正如其他人指出的那样,元素“2”与您提供的数据相匹配。

于 2013-06-05T10:59:38.840 回答