Search code examples
c#xmllinq

C# - Can I select the value of an XML attribute by searching for a second attribute?


I want to select the value of the "data" attribute where the "key" attribute matches a specific search.

The XML file will look like this.

<connections>
  <production>
    <connection key="KEY1" data="value1" />
    <connection key="KEY2" data="value2" />
    <connection key="KEY3" data="value3" />
  </production>
</connections>

So is there a way to return the value of the data attribute by searching for key = key1 for example?


Solution

  • You could do something like this if you wanted to avoid using XPath.

    using System.Xml.Linq;
    
    var xmlStr = File.ReadAllText("Testfile.xml");
    XElement root = XElement.Parse(xmlStr);
    var data = root.Element("production")
        .Elements().Where(x => x.Attribute("key").Value == "KEY1")
        .Select(x=>x.Attribute("data").Value)
        .First();
    Console.WriteLine(data);