• C#操作xml文件进行增、删、改


    进行操作的xml文件:

    products.xml 

    <?xml version="1.0" encoding="utf-8"?>
    <products>
    <product name="apple" price="3.50"/>
    <product name="banana" price="2.00"/>
    </products>  
    View Code 

    增加节点:

    XmlDocument doc = new XmlDocument();
    doc.Load("products.xml");
    XmlNode xn = doc.SelectSingleNode("products");
    XmlElement xe = doc.CreateElement("product");
    xe.SetAttribute("name","haha");
    xe.SetAttribute("price","13.20");
    xn.AppendChild(xe);
    doc.Save("products.xml")
    View Code 

    修改节点属性值:

    XmlDocument doc = new XmlDocument();
    doc.Load("products.xml");
    XmlNode xn = doc.SelectSingleNode("products");
    XmlNodeList xnList = xn.ChildNodes;
    if(xnList.Count > 0)
    {
        for(int i = xnList.Count - 1; i >= 0;i--)
        {
             XmlElement xe = (XmlElement)xnList.Item(i);
             if(xe.Attributes["name"].Value == "banana")
             {
                 xe.SetAttribute("price","1111");
             break;    
             }
        }
        doc.Save("products.xml")
    View Code 

     删除节点:

    XmlDocument doc = new XmlDocument();
    doc.Load("products.xml");
    XmlNode xn = doc.SelectSingleNode("products");
    XmlNodeList xnList = xn.ChildNodes;
    if(xnList.Count > 0)
    {
        for(int i = xnList.Count - 1; i >= 0;i--)
        {
             XmlElement xe = (XmlElement)xnList.Item(i);
             if(xe.Attributes["name"].Value == "banana")
             {
                 xn.RemoveChild(xe);
             }
        }
        doc.Save("products.xml")
    View Code 


  • 相关阅读:
    Dbcp2抛出org.apache.commons.dbcp2.LifetimeExceededException
    DbUtils使用时抛出Cannot get a connection
    Spring注解【非单例】
    Exception in thread java.lang.IllegalThreadStateException
    eclipse选中变量,相同变量高亮。
    git push 403
    java虚拟机能并发的启动多少个线程
    产品的随想
    【转载】学习新东西的唯一方法
    Mysql错误问题记录
  • 原文地址:https://www.cnblogs.com/hehaiquan/p/3180984.html
Copyright © 2020-2023  润新知