If linq is just for fun, old XmlDocument has method SelectSingleNode, accepting xpath
static void Main(string[] args)
{
var xmlval =@"<configuration><appSettings><add key='username1' value='password1'/><add key='username2' value='password2'/></appSettings></configuration>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlval);
for (int i = 1; i < 5; i++)
{
string key = "username" + i.ToString();
Console.WriteLine("Value for key {0} is {1}", key, getvalue(doc, key));
}
}
static string getvalue(XmlDocument doc, string key)
{
var e = (XmlElement)doc.SelectSingleNode(string.Format( "configuration/appSettings/add[@key='{0}']",key));
if (e == null)
return null;
else
return e.Attributes["value"].Value;
}