开发者

how to load xml configuration file in asp.net project

I have some configuration to be read once ,so I put these attributes in a xml file:

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

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

In java,I can read this file within the init method of a servlet using the jdom or dom4j. THen put these attributes in a List or a Map.

But in asp.net,I have no开发者_C百科 idea how to implement this,any suggestion?


This is assuming you're using c#. It basically reads the xml out using linq to xml into the classes defined. GetConfigItems will then return a List<> of the items. I haven't tested this, but it's along the right lines.

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();

    }
}


DavidGouge is on the right track here. However his ConfigHelper method GetConfigItems() should be structured as follows:

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;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜