0

I have a XML file as follows

 <configuration>
  <appSettings>
   <add key="username1" value="password1"/>
   <add key="username2" value="password2"/>
  </appsettings>
 </configuration>

I want to read the text in value field when i pass the key. How to do this is c#.

Thanks in advance.

Varun
  • 95
  • 3
  • 13
  • Possible duplicate of [reading from app.config file](https://stackoverflow.com/questions/2400097/reading-from-app-config-file) – barakcaf May 25 '17 at 09:57
  • 1
    This is generally a question that you would pose to Google rather than StackOverflow. – Abion47 May 25 '17 at 09:59
  • 1
    Possible duplicate of [How does one parse XML files?](https://stackoverflow.com/questions/55828/how-does-one-parse-xml-files) – Abion47 May 25 '17 at 09:59
  • The xml file is not the App.config file for the application. Still can i use " ConfigurationManager.AppSettings" ? – Varun May 25 '17 at 10:00

2 Answers2

2

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; 
}
vitalygolub
  • 735
  • 3
  • 16
0

You will have to parse the XML file, using Linq to XML or something like XmlDocument.

For example using XmlDocument , you could do something like this:

XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
            xmlDoc.Load("XMLFile1.xml"); // Load the XML document 

            // Get elements           
            XmlNodeList addElements = xmlDoc.GetElementsByTagName("add");
            XmlNode n = addElements.Item(0); //get first {add} Node

            //Get attributes
            XmlAttribute a1 = n.Attributes[0];
            XmlAttribute a2 = n.Attributes[1];

            // Display the results
            Console.WriteLine("Key = " + a1.Name + " Value = " + a1.Value);
            Console.WriteLine("Key = " + a2.Name + " Value = " + a2.Value);
Syl20
  • 117
  • 2
  • 18