查找具有特定属性的元素 (XPath-LINQ to XML)

时间:2021-04-03 05:27:31
XElement doc = XElement.Parse(
@"<Root>
<Child1>1</Child1>
<Child2 Select='true'>2</Child2>
<Child3>3</Child3>
<Child4 Select='true'>4</Child4>
<Child5>5</Child5>
</Root>"); // LINQ to XML query
IEnumerable<XElement> list1 =
from el in doc.Elements()
where el.Attribute("Select") != null
select el; // XPath expression
IEnumerable<XElement> list2 =
((IEnumerable)doc.XPathEvaluate("./*[@Select]")).Cast<XElement>(); if (list1.Count() == list2.Count() &&
list1.Intersect(list2).Count() == list1.Count())
Console.WriteLine("Results are identical");
else
Console.WriteLine("Results differ");
foreach (XElement el in list1)
Console.WriteLine(el);