1

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!

Wusiji
  • 599
  • 1
  • 7
  • 24
user2382465
  • 23
  • 1
  • 4

2 Answers2

1

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;
        }
Santosh Panda
  • 7,235
  • 8
  • 43
  • 56
  • Thanks for your answer. Unfortunately I tried that but childList result is always **empty**. Without the last where clause it answers:`+ [0] System.Xml.Linq.XElement` `+ [1] System.Xml.Linq.XElement` – user2382465 May 15 '13 at 11:57
  • @user2382465 But for me itz working fine. I can fetch the exact node. – Santosh Panda May 15 '13 at 12:24
  • Someone at work helped me, after the second Where clause I need to add something like "ToList" or in my case "FirstOrDefault". – user2382465 May 15 '13 at 14:16
1

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;
    }
user2382465
  • 23
  • 1
  • 4