【问题标题】:how to load xml configuration file in asp.net project如何在asp.net项目中加载xml配置文件
【发布时间】:2011-04-14 13:33:14
【问题描述】:

我有一些配置要读取一次,所以我将这些属性放在一个 xml 文件中:

<items>
  <item id="" name="">
    <page src=""/>
    <page src=""/>
    <page src=""/>
  </item>

  <item id="" name="">
    <page src=""/>
    <page src=""/>
    <page src=""/>
  </item>
............
</items>

在 java 中,我可以使用 jdom 或 dom4j 在 servlet 的 init 方法中读取此文件。 然后将这些属性放在 List 或 Map 中。

但是在asp.net中,我不知道如何实现这个,有什么建议吗?

【问题讨论】:

    标签: asp.net configuration


    【解决方案1】:

    这是假设您使用的是 c#。它基本上使用 linq to xml 将 xml 读取到定义的类中。 GetConfigItems 然后将返回项目的 List。我没有测试过这个,但它是正确的。

    public class Item
    {
        public string id { get; set; }
        public string name { get; set; }
        public List<Page> Pages { get; set; }
    }
    
    public class Page
    {
        public string src { get; set; }
    }
    
    public class ConfigHelper
    {
        public List<Item> GetConfigItems()
        {
            XDocument doc = XDocument.Load("MyConfigFile.xml");
            List<Item> items = (from i in doc.Elements("item")
                                select new Item()
                                    {
                                        id = i.Attribute("id").Value,
                                        name = i.Attribute("name").Value,
                                        Pages = (from p in i.Elements("page")
                                                 select new Page()
                                                 {
                                                     src = p.Attribute("src").Value
                                                 }).ToList()
                                    }
                               ).ToList();
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      DavidGouge 在这方面走在了正确的轨道上。然而,他的 ConfigHelper 方法 GetConfigItems() 的结构应该如下:

      public List<Item> GetConfigItems()
          {
              XDocument doc = XDocument.Load("MyConfigFile.xml");
              List<Item> items = (from i in doc.Descendants("item")
                                  select new Item()
                                  {
                                      id = i.Attribute("id").Value,
                                      name = i.Attribute("name").Value,
                                      Pages = (from p in i.Descendants("page")
                                               select new Page()
                                               {
                                                   src = p.Attribute("src").Value
                                               }).ToList()
                                  }).ToList();
              return items;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-29
        • 2011-01-08
        • 2017-07-08
        相关资源
        最近更新 更多