LINQ to XML: filter a query using the XElement.Attributes () collection using both XName and Value

Using LINQ to XML, XElements, and XAttributes, I would like to filter the query using the exact match in the XElement Attributes () collection of the IEnumerable XName / Value pairs, in relation to the provided set of IEnumerable Attributes attributes of the XName / Value pairs.

<container>
   <!-- logical group of settings -->
   <group name="group-one">
      <!-- setting with multiple key-value key options to return value -->
      <setting>
         <key app="a" command="go" />
         <key app="a" type="z" command="go" />
         <key app="a" type="z" flag="1" command="go" />
         <key app="a" type="z" target="OU812"/>
         <value>group-one item value A</value>
      </setting>
      <setting>
         <key app="a" />
         <key app="a" type="z" />
         <key app="a" type="z" flag="1" />
         <key app="c" type="z" command="go" />
         <value>group-one item value B</value>
      </setting>      
      ...
      ...
   </group>
   <group name="group-two">
      ...
      ...
   </group>
</container>

(). SequenceEqual() IEqualityComparer XAttribute.XName, XAttribute.Value - , , XElement ( "" ). () . linq, , "let", , .

var myAttributes = new List<XAttribute> {
                                        new XAttribute("app", "a"), 
                                        new XAttribute("type", "z")
                                        };

var xGroup = doc.Elements("group").First(g=>g.Attribute("name").Value==groupName);
var xSetting = (from s in xGroup.Elements("setting")
               // AttributesComparer() compares both the XAttribute.XName and XAttribute.Value properties to determine equality
               where s.Elements("key").Attributes().SequenceEqual(myAttributes, new AttributesComparer())
               select s).FirstOrDefault();

var xValue = xSetting.Element("value");

XElement, <value>group-one item value B</value>

XPathSelectElement() - XPath, / XAttributes(). :

group[@name='group-one']/setting[key[@app='n' and @type='z' and count(@*)=2]]/value

, , , . , , , , "" , linq- ( ) .

/ !

+3
1

, , Any. :

    var xSetting = (from s in xGroup.Elements("setting")
                    // AttributesComparer() compares both the XAttribute.XName and XAttribute.Value properties to determine equality
                    where s.Elements("key").Any(key => key.Attributes().SequenceEqual(myAttributes, new AttributesComparer()))
                    select s).FirstOrDefault();
+2

Source: https://habr.com/ru/post/1725998/


All Articles