简体   繁体   中英

Getting selected attribute value of an XML Document using C#

Below is my config xml file,where i have multiple username and password.From this i need to select xml nodes by username attribute values.

 <Authentication>
    <auth Userame="username1" Password ="xxxxxx"/>
    <auth Userame="username2" Password ="xxxxxxx"/>
    <auth Userame="username3" Password ="xxxxxx"/>
  </Authentication>

What i am trying is,I need to select the node with username2 and update the value of password for that node in xml.I am using XmlDocument and i can see lot of examples with XDocument for selecting attribute.Is it possible to perform this with XmlDocument in C#.

Currently i am doing with one node and for one node i implemented like below,

 XmlDoc.SelectSingleNode("Settings/Authentication/auth").Attributes["Password"].Value = password;
 XmlDoc.Save(path);

Please help me in doing this.

Slight modification to the XPath part of your code will do the job :

var username = "username2";
var xpath = String.Format("Settings/Authentication/auth[@Userame='{0}']", username);
XmlDoc.SelectSingleNode(xpath)
      .Attributes["Password"]
      .Value = password;

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