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>

如何在调试中阅读此内容?

4

2 回答 2

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());
    }
}
于 2013-04-15T11:23:45.023 回答
0

在 C# 中,我建议您使用 Linq to XML。它在标准 .net 框架 (3.5) 中,它可以帮助您加载 XML,并轻松读取它的每个节点和属性。

于 2013-04-15T11:01:09.843 回答