将数据插入xml文件 [英] Inserting data into xml file
本文介绍了将数据插入xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每当新客户在asp.net core 3.1中向网站注册及其详细信息时,我都希望将连接字符串更新为xml文件.
I want to update connection string into xml file whenever new customer is registered with the website with its details in asp.net core 3.1
我的连接字符串格式为
<ConnectionStrings>
<add name="myConnectionString1" connectionString="server=localhost;database=myDb1;uid=myUser1;password=myPass;" />
<add name="myConnectionString2" connectionString="server=localhost;database=myDb2;uid=myUser2;password=myPass;" />
</ConnectionStrings>
我想使用C#代码实现此目的,因此在注册时,该数据将自动在xml文件中更新
I want to achieve this using c# code so on registration this data will automatically updated in xml file
推荐答案
离我远去:
您可以按照以下步骤编辑现有的XML.
You can edit your existing XML as follows.
// Loads XML from file.
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\yourFile.xml");
// Get a list of all <ConnectionStrings> nodes.
XmlNodeList nodes = doc.SelectNodes("/ConnectionStrings");
// Loop through each found node.
foreach (XmlNode node in nodes)
{
// Search for the 'connectionString' attribute into the node.
XmlAttribute attrib = node.Attributes["connectionString"];
if (attrib != null)
{
// If the attribute could be found then you might want to get its value.
string currentValue = attrib.Value;
// Or do some stuff with the value. E.g: Set a new value based on the old one.
attrib.Value = currentValue + "your modification here";
}
}
// Finally you might want to save the document in other location.
doc.Save(@"C:\yourNewFile.xml";
编辑:根据要求,您可以按如下所示将新的连接字符串元素添加到连接字符串部分.(未经测试.可能需要进行一些调整)
As per requested you can add a new connection string element to your connection strings section as follows. (Not tested. It could require some adjustments)
using System.Configuration;
// Create a connection string element and add it to
// the connection strings section.
private bool CreateConnString(string name, string connString, string uId, string password)
{
try
{
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Get the current connection strings count.
int connStrCnt =
ConfigurationManager.ConnectionStrings.Count;
// Create a connection string element and
// save it to the configuration file.
// In your case 'connString' parameter should be
// something like "server=localhost;database=myDb1;"
ConnectionStringSettings csSettings =
new ConnectionStringSettings(name, connString +
"uid=" + uId + ";password=" + password + ";");
// Get the connection strings section.
ConnectionStringsSection csSection =
config.ConnectionStrings;
// Add the new element.
csSection.ConnectionStrings.Add(csSettings);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
return true;
}
catch (Exception e)
{
return false;
}
}
这篇关于将数据插入xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文