2016-01-27 2 views
0

нужно изменить атрибут с name = "SqlServer"Изменить атрибут XML C#

Config файл так же, как 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

awe, 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"; 
      } 
     } 

    } 
} 
Смежные вопросы