C#实现向xml中读写数据的简单示例

一、程序代码

//文件保存在当前程序所在目录
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Xml;

namespace ConsoleApp1
{
    enum LEVEL{
        INFO,
        Error,
        OK
    }
    enum STATUS
    {
        OUT,
        EXIST
    }
    class BOOK {
        public BOOK(Guid input_id,string input_name)
        {
            id = input_id;
            bookname = input_name;
            sTATUS = STATUS.EXIST;
        }
        public Guid id;
        public string bookname;
        public STATUS sTATUS;

    }

    static class Log
    {
        public static void output(LEVEL level,string format,params object[] arg)
        {
            ConsoleColor oldColor = Console.ForegroundColor;
            ConsoleColor newColor;
            switch (level)
            {
                case LEVEL.INFO:
                    newColor = oldColor;
                    break;
                case LEVEL.Error:
                    newColor = ConsoleColor.Red;
                    break;
                case LEVEL.OK:
                    newColor = ConsoleColor.Green;
                    break;
                default:
                    newColor = oldColor;
                    break;
            }
            Console.ForegroundColor = newColor;
            Console.WriteLine(format, arg);
            Console.ForegroundColor = oldColor;
        }
    } 
    class BOOKSys
    {
        Dictionary<string, string> database;
        Dictionary<Guid, BOOK> bookDB;
        public string username;
      
        public BOOKSys()
        {
            database = new Dictionary<string, string>();
            username = "";
            bookDB = new Dictionary<Guid, BOOK>();
            load_userMess();//程序启动时将信息载入字典中
            load_bookMess();
        }
        public string getDBpath()
        {
            string currentExepath = Assembly.GetExecutingAssembly().Location;
            string currentDir = Path.GetDirectoryName(currentExepath);
            string currentDB = Path.Combine(currentDir, "booksys.xml");
            return currentDB;
        }
        public void runCommand(string massage)
        {
            string[] command;
            command = massage.Split(' ');
            string commandName = command[0];
            switch (commandName)
            {
                case "reg": command_reg(command);break;
                case "login": command_login(command); break;
                case "add": command_Addbook(command); break;
                case "list": command_listbook(); break;
                case "save": command_save(); break;
                default: Log.output(LEVEL.Error, "command is error.");break;
            } 
        }
        public void command_Addbook(string[] command)
        {
            string bookname = command[1];
            string countStr = command[2];
            int count = Convert.ToInt32(countStr);//转化为int型
            for(int i = 0; i < count; i++)
            {
                Guid newid = Guid.NewGuid();
                BOOK bOOK = new BOOK(newid, bookname);
                bookDB[newid] = bOOK;
            }
            Log.output(LEVEL.OK, "book has successed sava in BOOKSys.");
        }
        public void command_listbook()
        {
            //var类型推断
            foreach(var bookpair in bookDB)
            {
                Log.output(LEVEL.INFO, "{0}  《{1}》  {2}", bookpair.Key, bookpair.Value.bookname, bookpair.Value.sTATUS);
            }
        }
        public void command_reg(string[] command)
        {
            string lowerUsername = command[1].ToLower();
            if (database.ContainsKey(lowerUsername))
            {
                Log.output(LEVEL.Error, "the user {0} has been registered already.", command[1]);
                return;
            }

            database[lowerUsername] = command[2];//command[1]为key,command[2]为value
            Log.output(LEVEL.OK, "the user {0} has been registered successfully!", command[1]);
            //Console.WriteLine("{0},{1}", command[1], command[2]);
        }
        public void command_login(string[] command)
        {
            string lowerUsername = command[1].ToLower();
            if (database.ContainsKey(lowerUsername))
            {
                if(database[lowerUsername] == command[2])
                {
                    Log.output(LEVEL.OK, "the user {0} has login successfully.", command[1]);
                    username = command[1];
                }
                else
                {
                    Log.output(LEVEL.Error, "the password is not right.");
                }
            }
            else
            {
                Log.output(LEVEL.Error, "the username {0} is not registered.",command[1]);
            }
        }

        public void command_save()
        {
            string DbName = getDBpath();
            XmlDocument xmlDb = new XmlDocument();//创建xml文件的操作对象
   
            XmlDeclaration dec = xmlDb.CreateXmlDeclaration("1.0",null,null);//创建xml头
            xmlDb.AppendChild(dec);//使相关联

            XmlElement bookNode = xmlDb.CreateElement("BOOKSYS");//创建bookNode结点
            xmlDb.AppendChild(bookNode);

            XmlElement userPassword = xmlDb.CreateElement("userPassword");//创建用户名密码的结点
            bookNode.AppendChild(userPassword);
            XmlElement bookMessage = xmlDb.CreateElement("bookMessage");//创建书籍信息结点
            bookNode.AppendChild(bookMessage);
            foreach(KeyValuePair<string,string> currUser in database)
            {
                //<BOOKSYS>
                //  <USER name = "ken",password = "123"/>
                //</BOOKSYS>
                //创建USER结点
                XmlElement userNode = xmlDb.CreateElement("USER");

                //创建USER结点中的name属性
                XmlAttribute name = xmlDb.CreateAttribute("name");
                //将用户键值对的key,也就是用户名,写入USER结点的name属性
                name.InnerText = currUser.Key;
                //给USER结点挂接name属性
                userNode.Attributes.Append(name);

                //创建USER结点中的password属性
                XmlAttribute password = xmlDb.CreateAttribute("password");
                //将用户键值对的value,也就是密码,写入USER结点的password属性
                password.InnerText = currUser.Value;
                //给USER结点挂接name属性
                userNode.Attributes.Append(password);

                //将user结点挂接到bookNode结点下
                userPassword.AppendChild(userNode);
            }
            foreach(KeyValuePair<Guid,BOOK> bookmes in bookDB)
            {
                XmlElement book = xmlDb.CreateElement("BOOK");

                XmlAttribute id = xmlDb.CreateAttribute("id");
                id.InnerText = bookmes.Key.ToString();
                book.Attributes.Append(id);

                //创建book结点中的name属性
                XmlAttribute name = xmlDb.CreateAttribute("name");
                //将书籍键值对的value中的bookname属性赋值给name
                name.InnerText = bookmes.Value.bookname;
                //给book结点挂接name属性
                book.Attributes.Append(name);

                XmlAttribute status = xmlDb.CreateAttribute("status");
                status.InnerText = bookmes.Value.sTATUS.ToString();
                book.Attributes.Append(status);

                bookMessage.AppendChild(book);
            }
            xmlDb.Save(DbName);
            Log.output(LEVEL.OK, "message has been save in computer successfully.");
        }

        public void load_userMess()
        {
            string user, password;
            string DbName = getDBpath();
            XmlDocument xmlDb = new XmlDocument();
            try
            {
                xmlDb.Load(DbName);//载入xml文件
                XmlNode xn = xmlDb.SelectSingleNode("/BOOKSYS/userPassword");//得到根节点
                                                                             //<BOOKSYS>
                                                                             //  <userPassword>
                                                                             //      <NODE1/>
                                                                             //      <NODE2/>
                                                                             //  </userPassword>
                                                                             //</BOOKSYS>
                XmlNodeList xnl = xn.ChildNodes;//获得根节点的所有子节点

                foreach (XmlNode x in xnl)
                {
                    user = x.Attributes["name"].Value;
                    password = x.Attributes["password"].Value;
                    database[user] = password;
                }
            }
            catch(Exception e){
                return;
            }
        }
        public void load_bookMess()
        {
            string DbName = getDBpath();
            XmlDocument xmlDb = new XmlDocument();
            try
            {
                xmlDb.Load(DbName);//载入xml文件
                XmlNode xn = xmlDb.SelectSingleNode("/BOOKSYS/bookMessage");//得到根节点
                XmlNodeList xnl = xn.ChildNodes;//获得根节点的所有子节点

                foreach (XmlNode x in xnl)
                {
                    string id, bookname;
                    id = x.Attributes["id"].Value;
                    bookname = x.Attributes["name"].Value;
                    //status = x.Attributes["status"].Value;
                    Guid gg = new Guid(id);//将字符串类型的guid转化为guid
                    BOOK b = new BOOK(gg, bookname);
                    bookDB[gg] = b;
                }
            }catch(Exception e)
            {
                return;
            }
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            /*
             *double[] balance = new double[10];
             double[] balance = { 2340.0, 4523.69, 3421.0};
             int [] marks = new int[5]  { 99,  98, 92, 97, 95};
             int [] marks = new int[]  { 99,  98, 92, 97, 95};
             
             int [] marks = new int[]  { 99,  98, 92, 97, 95};
             int[] score = marks;
             
             */
            
            BOOKSys bOOKSys = new BOOKSys();
            string command;
            while(true)
            {
                if(bOOKSys.username != "")
                {
                    Console.Write("{0} @ ", bOOKSys.username);
                }
                Console.Write("BOOKSYS >");
                command = Console.ReadLine();
                if(command == "exit")
                {
                    break;
                }
                bOOKSys.runCommand(command);
            }
            
            Console.Read();

        }


    }
}


二、效果演示

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值