C# 读取XML文件和写入XML文件

对XML文件进行操作(写入,读取)时需要引用命名空间

using System.IO;

using System.Xml;

写入XML文件

创建文件流对象

创建StreamWriter对象,传入参数(文件流,文字编码模式)

调用StreamWriter对象的WriteLine方法就可以向文件中写入数据了

            try
            {
                FileStream fs = new FileStream(@"LrcColor.xml",FileMode.Create);
                StreamWriter sw = new StreamWriter(fs,Encoding.Default);
                sw.WriteLine("");
                sw.WriteLine("");
                sw.Write("");
                sw.Write("unplaying");
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.unplayingColor.A);
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.unplayingColor.B);
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.unplayingColor.G);
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.unplayingColor.R);
                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("");
                sw.Write("");
                sw.Write("playing");
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.playingColor.A);
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.playingColor.B);
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.playingColor.G);
                sw.WriteLine("");
                sw.Write("");
                sw.Write(this.playingColor.R);
                sw.WriteLine("");
                sw.WriteLine("");
                sw.WriteLine("");
                sw.Close();
                fs.Close();
            }
            catch (Exception)
            {
                return;
            }    

 

读取XML文件

       XmlDocument xml = new XmlDocument();
            xml.Load("LrcColor.xml");
            XmlNode xmlNode = xml.DocumentElement;
            foreach (XmlNode node in xmlNode.ChildNodes)
            {
                foreach (XmlNode childNodes in node.ChildNodes)
                {
                    switch (childNodes.InnerText)
                    {
                        case "unplaying":
                            this.unplayingColor = Color.FromArgb(Convert.ToInt32(node["colorA"].InnerText), Convert.ToInt32(node["colorR"].InnerText), Convert.ToInt32(node["colorG"].InnerText), Convert.ToInt32(node["colorB"].InnerText));
                            break;
                        case "playing":
                            this.playingColor = Color.FromArgb(Convert.ToInt32(node["colorA"].InnerText), Convert.ToInt32(node["colorR"].InnerText), Convert.ToInt32(node["colorG"].InnerText), Convert.ToInt32(node["colorB"].InnerText));
                            break;
                    }
                }
            }

 

 

转载于:https://www.cnblogs.com/BrightMoon/archive/2013/02/24/2924285.html

你可能感兴趣的:(C# 读取XML文件和写入XML文件)