心 涯

NET&JAVA&PHP(要跨界,你不只要跨「脑」的界限,更要跨越「心」的界限,不怕改变,不怕再学习!)

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
1.利用Linq创建一个XML

//Create dummy XML to work

var root = new XElement("parent",

    from i in new int[] { 1, 2, 3, 4, 5, 6 }

    select new XElement("child",

        new XAttribute("number", i)));

This will create XML like,

<?xmlversion="1.0"encoding="utf-8"?>

<parent>

 <childnumber="1" />

 <childnumber="2" />

 <childnumber="3" />

 <childnumber="4" />

 <childnumber="5" />

 <childnumber="6" />

</parent>

2.查询添加Xml节点

//Get the element (child3)

XElement child3 = root.Descendants("child").First(

    el => (int)el.Attribute("number") == 3);

//Add element before the child3

child3.AddBeforeSelf(new XElement("child25"));

//Add sub-element to the child3

child3.Add(new XElement("grandchild"));

//Add element after the child3

child3.AddAfterSelf(new XElement("child35"));

//Add attribute to the child3

child3.Add(new XAttribute("attr", "something"));

//Change the existing attribute

child3.SetAttributeValue("number", 100);



After all these activities you will get the following output,

<?xmlversion="1.0"encoding="utf-8"?>

<parent>

 <childnumber="1" />

 <childnumber="2" />

 <child25 />

 <childnumber="100"attr="something">

    <grandchild />

 </child>

 <child35 />

 <childnumber="4" />

 <childnumber="5" />

 <childnumber="6" />

</parent>


3.删除Xml节点
child3.Remove();

posted on 2008-04-05 23:12  witer666  阅读(595)  评论(0编辑  收藏  举报