实用地更改web.config安全模式(编辑XML文件)

时间:2014-10-30 09:46:33

标签: c# xml xmldocument

如果我们的配置看起来像这样......

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <services>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="serviceConfiguration" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:01:00" sendTimeout="00:01:00" maxReceivedMessageSize="33554432" messageEncoding="Text" textEncoding="utf-8">
            <readerQuotas maxDepth="32" maxStringContentLength="524288" maxArrayLength="1048576"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    </system.serviceModel>
</configuration>

我想改变

<security mode="TransportCredentialOnly"><security mode="Transport">

<transport clientCredentialType="Windows" /><transport clientCredentialType="None" />

到目前为止,我已阅读xml文件并阅读安全节点

        WebConfig = @"c:\xml.xml";

        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load(WebConfig);

        XmlNodeList oldNodes;
        oldNodes = myXmlDocument.GetElementsByTagName("security");

但我不确定如何更改XML节点并将其保存回文件。

我们需要这样做,因为有时我们必须在部署后手动更改配置,并且有数百个,所以我务实地递归浏览文件并结束它们。

1 个答案:

答案 0 :(得分:0)

如果您想继续使用XmlDocument,可以按照此示例按名称和特定属性值选择元素:

....

//select <security> element having mode attribute value equals "TransportCredentialOnly"
XmlNode security = myXmlDocument.SelectSingleNode("//security[@mode='TransportCredentialOnly']");
if(security != null)
{
    //edit the attribute value
    security.Attributes["mode"].Value = "Transport";
}

....

//save edited XmlDocument back to file    
myXmlDocument.Save(WebConfig);