xml文件的读写操作

1.直接上代码:包含了xml文档的创建读取xml文档,创建根节点,向根节点中添加子节点,保存xml文档----------先来张效果图:

 

static void Main(string[] args)
        {
            //追加XML文档
            XmlDocument doc = new XmlDocument();
            XmlElement books;
            if (File.Exists("Books.xml"))
            {
                //如果文件存在 加载XML
                doc.Load("Books.xml");
                //获得文件的根节点
                books = doc.DocumentElement;
            }
            else
            {
                //如果文件不存在
                //创建第一行
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                //创建跟节点
                books = doc.CreateElement("Books");
                doc.AppendChild(books);
            }
            //5、给根节点Books创建子节点
            XmlElement book1 = doc.CreateElement("Book");
            //将book添加到根节点
            books.AppendChild(book1); 


            //6、给Book1添加子节点
            XmlElement name1 = doc.CreateElement("Name");
            name1.InnerText = "c#开发大全";
            book1.AppendChild(name1);

            XmlElement price1 = doc.CreateElement("Price");
            price1.InnerText = "110";
            book1.AppendChild(price1);

            XmlElement des1 = doc.CreateElement("Des");
            des1.InnerText = "看不懂";
            book1.AppendChild(des1);


            doc.Save("Books.xml");
            Console.WriteLine("保存成功");
            Console.ReadKey();

        }

2.操作xml文档,读取标签的属性修改标签的属性


//读取带属性的XML文档
XmlDocument doc = new XmlDocument();
doc.Load("Order.xml");

//获取节点的集合
XmlNodeList xnl = doc.SelectNodes("/Order/Items/OrderItem");

foreach (XmlNode node in xnl)
{

//获取节点Name属性的值
  Console.WriteLine(node.Attributes["Name"].Value);

//获取节点Count属性的值
  Console.WriteLine(node.Attributes["Count"].Value);
}

3.操作xml文档,删除信息

        //创建文档对象
            XmlDocument doc = new XmlDocument();
            //加载xml文档
            doc.Load("Order.xml");
            //选出要删除节点的集合
            XmlNode xn = doc.SelectSingleNode("/Order/Items");
            //移除
            xn.RemoveAll();
            //保存
            doc.Save("Order.xml");
            Console.WriteLine("删除成功");
            Console.ReadKey();

 

转载于:https://www.cnblogs.com/gchlcc/p/5004918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值