tags:

views:

73

answers:

1

Here is the xml I am trying to access:

<resourceStrings>    
    <globalStrings>
          <string>
             <key>RptTitle1</key>
             <value>Title1</value>
           </string>    
           <string>
              <key>RptTitle2</key>
              <value>ReportTitle2</value>
           </string>
            <string>
                <key>RptTitle3</key>
                <value>ReportTitle3</value>
            </string>
       </globalStrings>
</resourceStrings>

How would I use linq to xml to search for key of RptTitle1 and return the value of the value node?

+3  A: 

Like this:

var doc = XDocument.Load(...);

var setting = doc.Descendants("string").First(e => e.Element("key").Value == "RptTitle1");
var RptTitle1 = setting.Element("value").Value;

This code will find the first <string> element that has a <key> element with a value equal to RptTitle1, then get that element's <value> element.

SLaks
I get an error when trying to use the .First method.
TampaRich
Add `using System.Linq;` to the top of your file. If you still get an error, add a reference to System.Core.dll to your project.
SLaks
got it, no errors. I thought all I needed was System.Xml.Linq.
TampaRich
@TampaRich: System.Xml.Linq is needed for the `XDocument`, `XElement`, etc classes. System.Core and System.Linq are needed for the generic Linq-to-Objects methods (like `First`).
Martinho Fernandes