2014-10-30 80 views
0

如果我們有一個配置,看起來像這樣...更改web.config中的安全模式務實(編輯XML文件)

<?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

你可能要考慮使用[ConfigurationManager中(HTTP:/ /msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx)class。它專爲處理配置文件而設計,而不是滾動您自己的更通用的xml代碼。您應該找到強類型的類,它們代表您可以直接將其轉換爲文件的每個部分,並使用屬性等,而不是按名稱搜索。 – 2014-10-30 10:05:21

+0

另外,如果你想堅持'XmlDocument' - [這個問題](http://stackoverflow.com/questions/2558787/how-to-modify-exiting-xml-file-with-xmldocument-and-xmlnode- in-c-sharp?rq = 1)以正確的方式做出回答。 – 2014-10-30 10:09:44

回答

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);