Search code examples
linqattributeswhere-clausexelement

How to find XElement specific Children (in c# with LINQ)?


I've got an XML file like this :

<root>
 <environment env="PROD">
  <key name="Big Key" propagate="true" value="21" />
 </environment>
 <environment env="PRE-PROD">
  <key name="First Key" propagate="true" value="4" />
  <key name="Second Key" propagate="true" value="3" />
 </environment>
</root>

I want to check if a key exist in that file, and if the propagate item is true. I manage to get those 2 System.Xml.Linq.XElement : key name="First Key" AND key name="Second Key". but I would like to get only the one by pKeyname (like "Second Key" for eg.) I can't find how...

public static bool IsPropagate(string pXmlFileName, string pEnvironment, string pKeyname)
{
var doc = XElement.Load(pXmlFileName);
IEnumerable<XElement> childList = doc.Elements("environment")
.Where(elt => elt.Attribute("env").Value == pEnvironment)
.Elements();

if (childList.Any())
return true;
return false;
}

Any help would be highly appreciated!


Solution

  • This would help to get the exact key:

           public static bool IsPropagate(string pXmlFileName, string pEnvironment, 
                                          string pKeyname)
            {
                var doc = XElement.Load(pXmlFileName);
                IEnumerable<XElement> childList = doc.Elements("environment")
                .Where(elt => elt.Attribute("env").Value == pEnvironment)
                .Elements()
                .Where(a => a.Attribute("name").Value == pKeyname);
    
                if (childList.Any())
                    return true;
                return false;
            }