利用Linq to XML 对XML操作

前面一篇文章我们已经介绍了XDocument的相关属性的,这一节我们就分享一下Linq to XML 对XML操作。

本节导读:

一、创建XML文档

二、增加XElement节点

三、删除XElement节点

四、修改XElement节点

五、查询XML中的元素


一、创建XML文档

创建一个xml文档,名称为sample.xml,路径xml/sample.xml。同时创建声明,xml版本号为1.0,字符集为utf-8,独立模式。

在xml中创建一个根节点:名称为“pictures”。

private void CreateXML()
   {
       string filePath=Server.MapPath("xml/sample.xml");
       if (!File.Exists(filePath))
       {              
           XDocument xdoc = new XDocument();
           //创建Xml的声明
           XDeclaration xdeclaration = new XDeclaration("1.0", "utf-8", "yes");
           xdoc.Declaration = xdeclaration;
           //创建根节点

          //注意:一定要创建一个节点,在保存,否则会报“处于状态 Document 的标记 EndDocument 将导致无效的 XML 文档”异常。
           xdoc.Add(new XElement("pictures"));
           //保存xml文件            
           xdoc.Save(filePath);
       }
   }

 

二、增加XElement节点

在之前创建的xml的根节点增加子节点picture,picture有属性id,下面有四个子节点,分别为name,src,order和description,

其中picture的属性自增1,代码实现如下:

private void AddXElement()
   {

       string filePath = Server.MapPath("xml/sample.xml");
       XDocument xdoc = XDocument.Load(filePath);
       int id = 1;
       if (xdoc.Root.Elements().Count()>0)
       {
           id = (from p in xdoc.Root.Elements() select new { id = int.Parse(p.Attribute("id").Value) }).Max(p => p.id) ;
           id = id + 1;
       }
     
       //创建子节点

       XElement pic1 = new XElement("picture");
       pic1.SetAttributeValue("id", id);
       pic1.SetElementValue("name", "Picture "+id.ToString());
       pic1.SetElementValue("src", id.ToString()+".jpg");
       pic1.SetElementValue("order", id.ToString());
       pic1.SetElementValue("description", id.ToString());       
       xdoc.Root.Add(pic1);
       xdoc.Save(filePath);
       txtShow.Text = xdoc.ToString();
   }

三、删除XElement节点

删除xml中picture属性ID最大的那个元素,注意Single方法是,一定要确保返回值只有一条记录,否则会引发异常。

这就要求我们为picture点设置属性ID的时候,一定保持ID的唯一性,类似数据库中表的主键一样,不能重复。

private void DeleteXElement()
   {
       string filePath = Server.MapPath("xml/sample.xml");
       XDocument xdoc = XDocument.Load(filePath);
       //删除ID最大的那个元素
       int id = (from p in xdoc.Root.Elements() select new { id = int.Parse(p.Attribute("id").Value) }).Max(p => p.id);
       xdoc.Root.Elements().Single(p => p.Attribute("id").Value == id.ToString()).Remove();
       xdoc.Save(filePath);
       txtShow.Text = xdoc.ToString();
   }

四、修改XElement节点

要修改xml中的某一节点,首先要找到这个节点,然后在更新相关的内容,在保存就可以了。下面更新的是xml文档中picture属性ID最大的元素,

把其name属性改为:“modifed name”。

private void UpdateXElement()
    {
        string filePath = Server.MapPath("xml/sample.xml");
        XDocument xdoc = XDocument.Load(filePath);
        //更新ID最大的那个元素
        int id = (from p in xdoc.Root.Elements() select new { id = int.Parse(p.Attribute("id").Value) }).Max(p => p.id);
        XElement element= xdoc.Root.Elements().First(p => p.Attribute("id").Value == id.ToString());
        element.SetElementValue("name", " modifed name");
        xdoc.Save(filePath);
        txtShow.Text = xdoc.ToString();
    }

五、查询XML中的元素

下面我们要实现的是,把xml中picture属性ID小于10 的元素找出来,并在DataGrid上显示出来。

private void ShowXML()
    {
        string filePath = Server.MapPath("xml/sample.xml");
        XDocument xdoc = XDocument.Load(filePath);
        var items = from p in  xdoc.Root.Elements()
                    where (int.Parse(p.Attribute("id").Value)<10)
                    select new { id=p.Attribute("id").Value,
                                 name = p.Element("name").Value,
                                 src = p.Element("src").Value
                    };
        dgShow.DataSource=items;
        dgShow.DataBind();
    }


终于把这篇文章写完了,欢迎大家评论指教。

posted @ 2011-05-09 16:21  顾思行  阅读(913)  评论(0编辑  收藏  举报