c# 操作XML

2021-04-09 00:28

阅读:593

标签:help   .com   lin   console   .text   ==   document   void   ace   

实例:增删改查

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace ConsoleApp1
{
    public class XMLHelper
    {
        public void Add()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");

            var root = doc.DocumentElement;

            var newnode = doc.CreateNode("element", "student", "");
          

            var newnode1 = doc.CreateNode("element", "sno", "");
            newnode1.InnerText = "4";
            var newnode2 = doc.CreateNode("element", "sname", "");
            newnode2.InnerText = "成龙";

            newnode.AppendChild(newnode1);
            newnode.AppendChild(newnode2);


            root.AppendChild(newnode);


            doc.Save("XMLFile1.xml");            
        }

        public void Delete()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");

            var root = doc.DocumentElement;

            root.RemoveChild(root.FirstChild);
            
            doc.Save("XMLFile1.xml");
        }

        public void Update()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");

            var root = doc.DocumentElement;

            var first = root.FirstChild.FirstChild;
            first.InnerText = "fffffffffff";

            doc.Save("XMLFile1.xml");
        }

        public void GetNodes()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");

            var root = doc.DocumentElement;
            var find = root.ChildNodes[1].InnerText;
            Console.WriteLine(find);
        }

        public void GetOneNodeByName()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");

            var root = doc.DocumentElement;

            foreach (XmlElement item in root.ChildNodes)
            {
                if(item.FirstChild.InnerText == "4")
                {
                    Console.WriteLine(item.OuterXml);
                }
            }
        }
    }
}

 技术分享图片

 

c# 操作XML

标签:help   .com   lin   console   .text   ==   document   void   ace   

原文地址:https://www.cnblogs.com/ligenyun/p/9072617.html


评论


亲,登录后才可以留言!