Linq To Xml操作XML增删改查

对XML文件的操作在平时项目中经常要运用到,比如用于存放一些配置相关的内容;本文将简单运用Linq TO Xml对XML进行操作,主要讲解对XML的创建、加载、增加、查询、修改以及删除;重点在于类XDocument、类XElement;本实例是在控制台程序运行,所以对加载的XML文件路径要注意,若XML文件不是代码自运创建时要设置其“复制到输出目录”-始终复制

1:首先看一下实例要加载的XML文件格式:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
  <User>
    <UserID>1</UserID>
    <UserName>踏浪帅</UserName>
  </User>
  <User>
    <UserID>2</UserID>
    <UserName>wujunyang</UserName>
  </User>
  <User>
    <UserID>3</UserID>
    <UserName>cnblogs</UserName>
  </User>
</Root>

 

2:[加载XML]加载XML文件的内容,假如XML文件不存在则创建一个CreateXmlFile(XmlFile):

            string XmlFile=Directory.GetCurrentDirectory()+"//XmlFile//UserXmlFiles.xml";
            if (!File.Exists(XmlFile))
            {
                CreateXmlFile(XmlFile);
            }
            XDocument xdocument = XDocument.Load(XmlFile);    //asp.net  XDocument.Load(Server.MapPath("//XmlFile//UserXmlFile.xml"));

            Console.WriteLine("--------------开始遍历XML节点内容--------------");
            var Users = from userInfo in xdocument.Element("Root").Elements() select new { UserID = userInfo.Element("UserID").Value, UserName = userInfo.Element("UserName").Value };
            foreach (var item in Users)
            {
                Console.WriteLine(string.Format("用户ID为:{0};名字为:{1}", item.UserID, item.UserName));
            }

运行结果:

3:[创建XML]上面提到假如XML文件不存在则创建一个,并增加我们想要的节点内容

        /// <summary>
        /// 生成XML文件
        /// </summary>
        /// <param name="XmlFile">XML保存的路径</param>
        private static void CreateXmlFile(string XmlFile)
        {
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), CreateXElement());
            xdoc.Save(XmlFile);
        }

        private static XElement CreateXElement()
        {
            XElement root = new XElement("Root",new XElement("User",new XElement("UserID","1"),new XElement("UserName","踏浪帅")),
                new XElement("User", new XElement("UserID", "2"), new XElement("UserName", "wujunyang")),
                new XElement("User", new XElement("UserID", "3"), new XElement("UserName", "cnblogs")));
            return root;
        }

4:[带条件遍历]带条件进行查询出想要的结果,这边我们查找UserID的值大于1

            Console.WriteLine("--------------开始带条件遍历XML节点内容--------------");
            var UserForWhere = from userInfo in xdocument.Element("Root").Elements() where Convert.ToInt32(userInfo.Element("UserID").Value) > 1 select new { UserID = userInfo.Element("UserID").Value, UserName = userInfo.Element("UserName").Value };
            foreach (var item in UserForWhere)
            {
                Console.WriteLine(string.Format("用户ID为:{0};名字为:{1}", item.UserID, item.UserName));
            }

运行结果:

5:[插入]往XML插入我们想要的值,此处我们再增加一个

            Console.WriteLine("--------------往XML文件里再插入一个节点的内容--------------");
            XElement InsertRoot = new XElement("User", new XElement("UserID", "4"), new XElement("UserName", "厦门"));
            xdocument.Element("Root").Add(InsertRoot);
            xdocument.Save(XmlFile);
            Console.WriteLine("插入节点成功");

运行结果:

XML文件内容变成:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
  <User>
    <UserID>1</UserID>
    <UserName>踏浪帅</UserName>
  </User>
  <User>
    <UserID>2</UserID>
    <UserName>wujunyang</UserName>
  </User>
  <User>
    <UserID>3</UserID>
    <UserName>cnblogs</UserName>
  </User>
  <User>
    <UserID>4</UserID>
    <UserName>厦门</UserName>
  </User>
</Root>

6:[更新]对节点下某个值进行更新,通过条件进行查找出来再更新

            Console.WriteLine("--------------更新XML文件里节点的内容--------------");
            XElement UserUpdate = (from userInfo in xdocument.Element("Root").Elements() where Convert.ToInt32(userInfo.Element("UserID").Value) == 3 select userInfo).SingleOrDefault();
            if (UserUpdate != null)
            {
                UserUpdate.Element("UserName").Value = "www.cnblogs.com/wujy";
                xdocument.Save(XmlFile);
            }
            Console.WriteLine("更新节点成功");

运行结果:

7:[删除]针对某个条件对XML中的某一项进行删除

            Console.WriteLine("--------------删除XML文件里节点的内容--------------");
            XElement UserDelete = (from userInfo in xdocument.Element("Root").Elements() where Convert.ToInt32(userInfo.Element("UserID").Value) == 2 select userInfo).SingleOrDefault();
            if (UserDelete != null)
            {
                UserDelete.Remove();
                xdocument.Save(XmlFile);
            }
            Console.WriteLine("删除节点成功");

运行结果:

 

8:除的上面提到值还有一种是属性如下面:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
  <User UserName="wujy" PassWord="76543" Age="30" />
  <User UserName="cnblogs" PassWord="23456" Age="26" />
  <User UserName="踏浪帅" PassWord="4567" Age="34" />
</Root>

最近碰到一字符串的XML,接着我们就实现把它转化为一个实体:

    public class User 
    {
        public string UserName { get; set; }

        public string PassWord { get; set; }

        public string Age { get; set; }
    }
        private static void CreateXmlFile(string XmlFile)
        {
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), CreateXElement());
            xdoc.Save(XmlFile);
        }

        private static XElement CreateXElement()
        {
            XElement root = new XElement("Root", new XElement("User", new XAttribute("UserName", "wujy"), new XAttribute("PassWord", "76543"), new XAttribute("Age", "30")),
                new XElement("User", new XAttribute("UserName", "cnblogs"), new XAttribute("PassWord", "23456"), new XAttribute("Age", "26")),
                new XElement("User", new XAttribute("UserName", "踏浪帅"), new XAttribute("PassWord", "4567"), new XAttribute("Age", "34")));
            return root;
        }


        public static List<User> DindDB()
        {
            List<User> list = new List<User>();
            XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), CreateXElement());
            string XmlStr = xdoc.ToString();
            byte[] ARRAY=Encoding.UTF8.GetBytes(cleanStringEmpty(XmlStr));
            MemoryStream stream=new MemoryStream(ARRAY);
            StreamReader READER=new StreamReader(stream);
            XDocument xmdo = XDocument.Load(READER);

            var ResultUsers = from userInfo in xmdo.Elements("Root").Elements("User") select new { UserName = userInfo.Attribute("UserName").Value, PassWord = userInfo.Attribute("PassWord").Value, Age = userInfo.Attribute("Age").Value };
            foreach (var item in ResultUsers)
            {
                User model = new User();
                model.UserName = item.UserName;
                model.PassWord = item.PassWord;
                model.Age = item.Age;
                list.Add(model);
            }
            return list;
        }

        private static string cleanStringEmpty(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                StringBuilder sb = new StringBuilder();
                string[] newStr = str.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < newStr.Length; i++)
                {
                    sb.Append(newStr[i].Trim());
                }
                return sb.ToString();
            }
            else
            {
                return null;
            }
        }

 

 

 如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】按钮,若有不足欢迎指正。  因为,我的写作热情也离不开您的肯定支持。
 
感谢您的阅读(源代码下载

posted @ 2013-10-13 17:04  踏浪帅  阅读(7209)  评论(2编辑  收藏  举报