对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("<LrcChannels>"); sw.WriteLine("<lrcColor>"); sw.Write("<playState>"); sw.Write("unplaying"); sw.WriteLine("</playState>"); sw.Write("<colorA>"); sw.Write(this.unplayingColor.A); sw.WriteLine("</colorA>"); sw.Write("<colorB>"); sw.Write(this.unplayingColor.B); sw.WriteLine("</colorB>"); sw.Write("<colorG>"); sw.Write(this.unplayingColor.G); sw.WriteLine("</colorG>"); sw.Write("<colorR>"); sw.Write(this.unplayingColor.R); sw.WriteLine("</colorR>"); sw.WriteLine("</lrcColor>"); sw.WriteLine("<lrcColor>"); sw.Write("<playState>"); sw.Write("playing"); sw.WriteLine("</playState>"); sw.Write("<colorA>"); sw.Write(this.playingColor.A); sw.WriteLine("</colorA>"); sw.Write("<colorB>"); sw.Write(this.playingColor.B); sw.WriteLine("</colorB>"); sw.Write("<colorG>"); sw.Write(this.playingColor.G); sw.WriteLine("</colorG>"); sw.Write("<colorR>"); sw.Write(this.playingColor.R); sw.WriteLine("</colorR>"); sw.WriteLine("</lrcColor>"); sw.WriteLine("</LrcChannels>"); 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; } } }