如果select single node为null,则创建单个节点

时间:2012-02-08 18:22:28

标签: c# xml xpath xmlnode selectsinglenode

我有一个更新配置文件的程序。例如,配置文件可能包含:

<configuration>
  <userSettings>
    <setting name="phoneNumber" serializeAs="String">
      <value>123-456-7890</value>
    </setting>
  </userSettings>
</configuration>

要更新此配置文件,请使用以下命令:

XmlNode phoneNumberNode = theConfig.SelectSingleNode("configuration/userSettings/setting[@name='phoneNumber']");
phoneNumberNode.FirstChild.InnerText = this._cloudPublisherWebURL;

现在,在更新期间我想更新phoneNumber和地址。地址可能在配置文件中,也可能不是

如果SelectSingleNode为null,我想创建一个具有给定路径的节点并设置其值。

XmlNode addressNode = theConfig.SelectSingleNode("configuration/userSettings/setting[@name='address']");
if(addressNode == null)
{
  //..Create the node here
}

如何在给定路径上创建具有值的节点?

1 个答案:

答案 0 :(得分:0)

XmlNode addressNode = theConfig.SelectSingleNode("configuration/userSettings");
XmlNode setting = addressNode.Item(0).SelectSingleNode("configuration/userSettings/setting[@name='phoneNumber']");

setting.SetAttribute("name", "address"); //this is to change the name attribute value into address