加载XML 添加删除节点

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;


namespace Example_Linq2Xml
{
    public class ContractManager
    {
        //文档根元素
        static XElement root = null;
        const string XML_PATH = "data.xml";

        static ContractManager()
        {
            if (!File.Exists(XML_PATH))
            {//如果XML文件不存在,则新建
                root = new XElement("通讯录");
                //root.Save(XML_PATH);
            }
            else
            {//否则从文件读取
                root = XElement.Load(XML_PATH);
            }
        }
        public static void Save()
        {//将内存中的数据保存至文件
            root.Save(XML_PATH);
        }

        public static IEnumerable<Contract> SelectAll()
        {//查询所有的联系人,通过投影返回Contract实体类集合
            return root.Elements("联系人").Select(
                e => new Contract
                {
                    Id=int.Parse(e.Attribute("Id").Value),
                    Name=e.Element("姓名").Value,
                    Address=e.Element("地址").Value,
                    Phone=e.Element("电话").Value
                }
            );
        }
        public static void Insert(Contract c)
        {//添加新的联系人节点
            int count = root.Elements("联系人").Count();
            root.Add(new XElement(
                "联系人",
                new XAttribute("Id",count+1),
                new XElement("姓名", c.Name),
                new XElement("地址", c.Address),
                new XElement("电话", c.Phone)
            ));
            //root.Save(XML_PATH);
        }

        public static void Update(Contract c)
        {//更新已有联系人节点
            var entity = root.Elements("联系人").SingleOrDefault(e=>e.Attribute("Id").Value==c.Id.ToString());
            if (entity == null) return;
            entity.Element("姓名").Value = c.Name;
            entity.Element("地址").Value = c.Address;
            entity.Element("电话").Value = c.Phone;
            //root.Save(XML_PATH);
        }

        public static void Delete(string id)
        {//删除指定Id的联系人节点
            var entity = root.Elements("联系人").SingleOrDefault(e => e.Attribute("Id").Value == id);
            entity.Remove();
            //root.Save(XML_PATH);
        }
    }
    [Serializable]
    public class Contract
    {//实体类
        public int Id{get;set;}
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
    }
}

posted @ 2012-04-22 19:51  微笑de『MY』  阅读(205)  评论(0编辑  收藏  举报