2016-01-27 98 views
0

需要與name = "SqlServer"更改XML屬性C#

配置文件就像XML,而不是從我的項目

<connectionStrings> 
    <add name="SqlServer" 
      connectionString="Data Source=192.168.1.1; Initial Catalog=s; Application Name=s; MultipleActiveResultSets = true; Pooling=True; User ID=1111;Password=1111;" />  

    <add name="SqlServer_WinAuthentication" 
      connectionString="Data Source=.; Initial Catalog=MeterShop; Integrated Security=True; Application Name=MeterShop; MultipleActiveResultSets = true; Pooling=True;" /> 

    <add name="SqlServer_SqlAuthentication" 
      connectionString="Data Source=.; Initial Catalog=MeterShop; User ID=1; Password=1; Application Name=1; MultipleActiveResultSets = true; Pooling=True;" /> 
</connectionStrings> 
+0

你有沒有嘗試什麼嗎?或者請顯示你所做的... –

+0

所有我所做的 - 只需加載xml,並獲得連接字符串的所有節點 –

+0

因此,您想添加一個新的節點或ConnectionStrings節點下的任何現有節點的更新名稱 –

回答

0

有很多方法可以改變屬性實現這一點,我更喜歡Linq到Xml

XDocument doc = XDocument.Parse(s); 
var target = doc.Descendants("connectionStrings")   
       .SingleOrDefault(e => e.Element("add").Attribute("name").Value == "SqlServer"); 

獲得目標元素後,您可以更新該值。

target.Element("add").Attribute("name").Value = "any thing you want"; 
doc.Save("filename"); // Save the file after your changes. 

工作Example

+0

敬畏,thx很多!) –

0

使用XML的LINQ

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication70 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string xml = 
      "<connectionStrings>" + 
       "<add name=\"SqlServer\"" + 
         " connectionString=\"Data Source=192.168.1.1; Initial Catalog=s; Application Name=s; MultipleActiveResultSets = true; Pooling=True; User ID=1111;Password=1111;\" />" + 
       "<add name=\"SqlServer_WinAuthentication\"" + 
         " connectionString=\"Data Source=.; Initial Catalog=MeterShop; Integrated Security=True; Application Name=MeterShop; MultipleActiveResultSets = true; Pooling=True;\" />" + 
       "<add name=\"SqlServer_SqlAuthentication\"" + 
         " connectionString=\"Data Source=.; Initial Catalog=MeterShop; User ID=1; Password=1; Application Name=1; MultipleActiveResultSets = true; Pooling=True;\" />" + 
      "</connectionStrings>"; 

      XElement connectionStrings = XElement.Parse(xml); 

      List<XAttribute> names = connectionStrings.Descendants("add").Select(x => x.Attribute("name")).ToList(); 
      foreach (XAttribute name in names) 
      { 
       name.Value = "123"; 
      } 
     } 

    } 
}