簡體   English   中英

使用C#編輯Xml文件

[英]edit Xml File using C#

這是我的xml文件...

->

<!--Daily Genarated File Path-->
<add key="DailyFilName" value="C:\DailySummary.xls"/>
<!--Weekly Genarated File Path-->
<add key="WeeklyFilName" value="C:\WeeklySummary.xls"/>
<!--Log File Path-->
<add key="LogFilName" value="c:\\TranmittalsLog.txt"/>

我需要通過c#編輯我的DailyFilName。 使用密鑰我需要更改值。

根據文件類型的不同,您可以使用許多選項。

如果它是標准XML文件,則可以使用內置的.NET類,例如XmlReaderXmlWriterXPathNavigator 在MSDN上可以找到示例。

如果它是一個app.config文件,則可以使用Configuration名稱空間直接使用該文件,而無需手動讀取/寫入Xml。 請查看MSDN上的ConfigurationManager類以獲取一些示例。

我認為如果您正在使用app.config文件,則需要此文件

ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = "C:\\App.config"};

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

config.AppSettings.Settings["SettingKey1"].Value = "newValue";
config.Save();

[注意:如果您試圖操縱app.config或web.config文件中的appSettings部分,建議使用ConfigurationManager

您可以執行以下操作:

    private void SetValue(String key, String value)
    {
        XDocument doc = XDocument.Load("...");
        XElement element = doc.Descendants("add").Where(d => d.Attribute("key") != null && d.Attribute("key").Value == key).First();
        element.Attribute("value").Value = value;
    }

用法

SetValue("DailyFilName", "...");
private void SetValue(string xmlFilePath, string key, string value)
{
   try
   {
      XDocument doc = XDocument.Load(xmlFilePath);
      XElement element = doc.Descendants("add").Where(d => d.Attribute("key") != null && d.Attribute("key").Value == key).First();
      element.Attribute("value").Value = value;
      doc.Save(xmlFilePath);
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.Message);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM