简体   繁体   中英

Extracting value from key in xml document using c#

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.

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; 
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM