LINQ to XML in C# where clause
I`ve got a piece in xml:
<result index="0" status="0">
<test field="aaa">value_a</test>
<test field="bbb">value_b</test>
<one>
<name></name>
<res1></res1>
</one>
<two>
<name></name>
<res2></res2>
</two>
<answer></answer>
<error></error>
</result>
var rez = from item in doc.Descendants("result")
where
开发者_开发知识库 select item;
foreach (var item in rez)
{
item.Element("res1").SetValue(x);
item.Element("res2").SetValue(y);
}
What do i write inside "where" to select an item ("result" block) where element "test" with attribute "aaa" has value_a, AND element "test" with an attribute "bbb" has value_b
There's a few different possibilities, but I chose to pull out the value pairs for clarity and maybe a slight performance improvement. If the # of test elements was high you could make testPairs a dictionary.
var rez = from item in doc.Descendants("result")
let testPairs = item.Elements("test")
.Select(t => Tuple.Create((string)t.Attribute("field"), (string)t)).ToArray()
where
testPairs.Any(t => t.Item1=="aaa" && t.Item2=="value_a") &&
testPairs.Any(t => t.Item1=="bbb" && t.Item2=="value_b")
select item;
I am not sure probably this is what you mean
where item.Element("test").Value == "something"
&& item.Element("test").Attribute("field").Value =="aaa"
精彩评论