zoukankan      html  css  js  c++  java
  • Linq(三)操作XML

    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();

  • 相关阅读:
    求最低价格
    A*算法入门
    hdu 4715
    手动扩大栈内存,让AC无忧
    hdu 4710
    hdu 1698
    poj3468区间延迟更新模板题
    hdu 1059二进制优化背包问题
    2059龟兔赛跑
    水1276
  • 原文地址:https://www.cnblogs.com/witer666/p/1138697.html
Copyright © 2011-2022 走看看