asp.net 实现xml插入与删除节点信息代码

作者:袖梨 2022-06-25

asp教程.net 实现xml插入与删除节点信息代码

下面实现向xml文件中的相应位置插入节点信息
 

 假设我们想通过插入节点将原来的xml文件结构变成如下所示
            lenovo      5000       black   
         ibm      10000      black     

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.xml;

namespace operatexml
{
    class program
    {
        static void main(string[] args)
        {
            try
            {
                //xml文件存储路径
                string myxmlfilepath = "e:mycomputers.xml";
                //向xml文件添加节点信息
                addxmlinformation(myxmlfilepath);
            }
            catch (exception ex)
            {
                console.writeline(ex.tostring());
            }
        }

        private static void addxmlinformation(string xmlfilepath)
        {
            try
            {
                xmldocument myxmldoc = new xmldocument();
                myxmldoc.load(xmlfilepath);
                //添加一个带有属性的节点信息
                foreach (xmlnode node in myxmldoc.firstchild.childnodes)
                {
                    xmlelement newelement = myxmldoc.createelement("color");
                    newelement.innertext = "black";
                    newelement.setattribute("ismixed", "yes");
                    node.appendchild(newelement);
                }
                //保存更改
                myxmldoc.save(xmlfilepath);
            }
            catch (exception ex)
            {
                console.writeline(ex.tostring());
            }
        }

    }
}

下面实现删除指定xml文件节点信息(即:将刚刚添加上的节点删除掉)代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.xml;

namespace operatexml
{
    class program
    {
        static void main(string[] args)
        {
            try
            {
                //xml文件存储路径
                string myxmlfilepath = "e:mycomputers.xml";
                //删除xml文件节点信息
                deletexmlinformation(myxmlfilepath);
            }
            catch (exception ex)
            {
                console.writeline(ex.tostring());
            }
        }

        private static void deletexmlinformation(string xmlfilepath)
        {
            try
            {
                xmldocument myxmldoc = new xmldocument();
                myxmldoc.load(xmlfilepath);
                foreach (xmlnode node in myxmldoc.firstchild.childnodes)
                {
                    //记录该节点下的最后一个子节点(简称:最后子节点)
                    xmlnode lastnode = node.lastchild;
                    //删除最后子节点下的左右子节点
                    lastnode.removeall();
                    //删除最后子节点
                    node.removechild(lastnode);
                }
                //保存对xml文件所做的修改
                myxmldoc.save(xmlfilepath);
            }
            catch (exception ex)
            {
                console.writeline(ex.tostring());
            }
        }

    }
}

相关文章

精彩推荐