首页 > Windows开发 > 详细

c# 操作XML

时间:2018-05-22 16:30:49      阅读:217      评论:0      收藏:0      [点我收藏+]

实例:增删改查

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!