5月,我们的纪念
2008-02
16

随便写的,非常之简陋,也算是刚接触linq to xml的学习笔记吧

GuestBook.Core项目是数据访问、逻辑层,所有的留言的增、删、改、查都实现IDataProvider接口,本例是用的LinqXmlProvider类来实现

有些东东没写完,如管理员模式、回复留言等。 

[code:c#]

public interface IDataProvider
    {
        void InsertMessage(GuestBookEntry msg);
        List<GuestBookEntry> GetData();
        List<GuestBookEntry> GetData(int StartIndex, int PageSize);
        void Reply(GuestBookEntry msg);
        void DeleteMessage(string id);
    }

[/code]

InsertMessage的部分代码

[code:c#]

 XElement doc = XDocument.Load(DataFile).Root;
           
            doc.Add(new XElement("Message",
                new XElement("ID", msg.ID),
                new XElement("content", new XCData(msg.Content)),
                new XElement("createdate", msg.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")),
                new XElement("Reply", msg.Reply),
                new XElement("Author",msg.Author),
                new XElement("IP", msg.IP)));
            doc.Save(DataFile);

[/code]

获取

[code:c#]

public List<GuestBookEntry> GetData(int StartIndex, int PageSize)
        {
            List<GuestBookEntry> List = new List<GuestBookEntry>();
            if (File.Exists(DataFile))
            {
                XDocument doc = XDocument.Load(DataFile);

                try
                {
                    var list = from a in
                                   (from c in doc.Descendants("Message")
                                    select new GuestBookEntry
                                    {
                                        Author = c.Element("Author").Value,
                                        Content = c.Element("content").Value,
                                        CreateDate = DateTime.Parse(c.Element("createdate").Value),
                                        ID = c.Element("ID").Value,
                                        IP = c.Element("IP").Value,
                                        Reply = c.Element("Reply").Value
                                    })
                               orderby a.CreateDate descending
                               select a;
                    List = new List<GuestBookEntry>(list.Skip(StartIndex).Take(PageSize));
                }
                catch { }

            }
            return List;
        }

[/code]

删除:

[code:c#]

public void DeleteMessage(string id)
        {
            XElement doc = XElement.Load(DataFile);
            var a = doc.Descendants("Message").Single(p => p.Element("ID").Value == id);
            a.Remove();
            doc.Save(DataFile);
           
        }

[/code]

 

 

guestbook.rar (53.67 kb)

Categories:   linq | .Net 3.5
Tags:  
Actions:   Comments (0) |

Add comment



(Will show your Gravatar icon)  



  Country flag


[b][/b] - [i][/i] - [u][/u]- [quote][/quote]

:-/ ^_^ :d :o :kiss: :) :p :se: [yeah] :( :love: :han: :up: :cry: :zzz: o_o


申请链接请看这里