码迷,mamicode.com
首页 > Windows程序 > 详细

c# 操作XML

时间:2018-05-22 16:36:47      阅读:248      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!