简体   繁体   English

使用C#获取XML文档的选定属性值

[英]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. 下面是我的配置xml文件,其中我有多个用户名和密码。从这里我需要通过username属性值选择xml节点。

 <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#. 我正在尝试的是,我需要选择具有用户名2的节点并在xml中更新该节点的密码值。我正在使用XmlDocument ,我可以看到很多使用XDocument来选择属性的示例。是否可以使用C#中的XmlDocument。

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 : 对代码的XPath部分进行少量修改即可完成此工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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