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

本文关键字:属性 文档 获取 XML 使用 | 更新日期: 2023-09-27 18:10:51

下面是我的配置xml文件,我有多个用户名和密码。从这里我需要通过username属性值选择xml节点。

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

我正在尝试的是,我需要选择具有username2的节点,并在xml中更新该节点的密码值。我使用XmlDocument,我可以看到很多XDocument选择属性的例子。是否可以在c#中使用XmlDocument来执行此操作?

目前我正在做一个节点和一个节点,我实现如下,

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

请帮我做这件事

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

只要稍微修改一下代码的XPath部分就可以了:

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