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!

有帮助吗?

解决方案

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;
        }

其他提示

It's working by adding the "FirstOrDefault"! Thanks.

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

        if (child != null)
            return true;
        return false;
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top