2013-04-15 57 views
0

我有配置看起來像這樣,我不知道如何閱讀,我想獲得價值,如果我選擇產品或預覽?使用不同的配置每個環境

<configuration> 

    <environment name="product"> 
    <connectionString> connection string</connectionString> 
    <logPath>C:\*****</logPath> 
    <errorLogPath>C:\*****</errorLogPath> 
    <ProcessesNumber>5</ProcessesNumber> 
     <sendAtOnce>100</sendAtOnce> 
    <restInterval>30000</restInterval> 
    <stopTime>30000</stopTime> 
</environment> 

<environment name="preview"> 
    <connectionString> connctionstring </connectionString> 
    <logPath>C:\*****</logPath> 
    <errorLogPath>C:\*****</errorLogPath> 
    <ProcessesNumber>5</ProcessesNumber> 
    <sendAtOnce>100</sendAtOnce> 
    <restInterval>30000</restInterval> 
    <stopTime>30000</stopTime> 
</environment> 

</configuration> 

如何在我的調試中讀取此內容?

+2

確實[這個答案](http://stackoverflow.com/a/3994081/266143)幫助?通過這種方式,每個版本都會創建一個'web。$(Configuration).config'文件,允許你有獨立的調試版本和發行版本配置。 – CodeCaster

回答

1

這是很容易使用LINQ

這會幫助你

class Configuration 
{ 
    public string connectionString { get; set; } 
    public string logPath { get; set; } 
    public string errorLogPath { get; set; } 
    public int ProcessesNumber { get; set; } 
    public int sendAtOnce { get; set; } 
    public int restInterval { get; set; } 
    public int stopTime { get; set; } 
} 

static void Main(string[] args) 
{ 
    try 
    { 
     XDocument doc = XDocument.Load("config.xml"); 
     string conftype = "product"; 

     var configuration = (from config in doc.Elements("configuration").Elements("environment") 
          where config.Attribute("name").Value.ToString() == conftype 
          select new Configuration 
          { 
           connectionString = config.Element("connectionString").Value.ToString(), 
           logPath = config.Element("logPath").Value.ToString(), 
           errorLogPath = config.Element("errorLogPath").Value.ToString(), 
           ProcessesNumber = int.Parse(config.Element("ProcessesNumber").Value.ToString()), 
           sendAtOnce = int.Parse(config.Element("sendAtOnce").Value.ToString()), 
           restInterval = int.Parse(config.Element("restInterval").Value.ToString()), 
           stopTime = int.Parse(config.Element("stopTime").Value.ToString()), 
          }).First(); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(e.ToString()); 
    } 
} 
+0

感謝您的分享,它正在工作。 –

+0

不客氣。請標記答案。謝謝。 – sarat

0

在C#中,我建議你使用Linq到XML。它位於標準的.NET框架(3.5)中,它可以幫助您加載XML,並輕鬆讀取每個節點和屬性。

相關問題