C#程序中:如何向xml文件中写入数据和读取数据

时间:2022-11-02 11:53:20

xml文件作为外部信息存储文件使用简单,方便,其结构和表格略有相似,下面简单的说一下xml文件内容的读取

……

using System.Xml;
using System.IO;
namespace WriteXml
{
    class Program
    {
        static void Main(string[] args)
        {
            createXml();

readXml();
        }

private static void createXml()
        {
            XmlTextWriter writer = new XmlTextWriter("titles.xml", null);
            //使用自动缩进便于阅读
            writer.Formatting = Formatting.Indented;

//写入根元素
            writer.WriteStartElement("items");
            writer.WriteStartElement("item");
            //加入子元素
            writer.WriteElementString("title", "毛著");
            writer.WriteElementString("author", "毛爷爷");
            writer.WriteElementString("price", "10.0");
            //关闭根元素,并书写结束标签
            writer.WriteEndElement();
            writer.WriteEndElement();
            //将XML写入文件并且关闭XmlTextWriter
            writer.Close();
        }

private static void readXml()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("titles.xml");
            XmlNode xn = xmlDoc.SelectSingleNode("items");
 
               XmlNodeList xnl=xn.ChildNodes;

foreach (XmlNode xnf in xnl)
               {
                   XmlElement xe = (XmlElement)xnf;
                   Console.WriteLine(xe.GetAttribute("类别"));//显示属性值
                   Console.WriteLine(xe.GetAttribute("品质"));

XmlNodeList xnf1 = xe.ChildNodes;
                   foreach (XmlNode xn2 in xnf1)
                   {
                       Console.WriteLine(xn2.InnerText);//显示子节点点文本
                   }
                   Console.WriteLine();
               }
        }

}
}

转:http://blog.sina.com.cn/s/blog_699337e60100ktcu.html