C#操作XML文件

1、创建、读取XML文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XML
{
    class Program
    {
        static void Main(string[] args)
        {
            
            if (!System.IO.File.Exists("Test.xml"))
            {
                CreateXML();
            }
            //读取XML文件
            System.Xml.Linq.XDocument xdoc = System.Xml.Linq.XDocument.Load("Test.xml");
            Console.WriteLine(xdoc.Element("root").Element("Test1").Value);
            Console.WriteLine(xdoc.Element("root").Element("Test2").Value);
            Console.WriteLine(xdoc.Element("root").Element("Test3").Value);

            //CreateXML2();
            
            Console.ReadKey();
        }
        /// <summary>
        /// 创建xml 方法一
        /// 利用System.Xml.Linq.XDocument
        /// </summary>
        private static void CreateXML()
        {
            //声明一个XML文件
            System.Xml.Linq.XDocument xdoc = new System.Xml.Linq.XDocument();
            //声明一个元素
            System.Xml.Linq.XElement eRoot = new System.Xml.Linq.XElement("root");
            //在XML文件中添加新建元素
            xdoc.Add(eRoot);
            //设置元素内容
            eRoot.SetElementValue("Test1", "1");
            eRoot.SetElementValue("Test2", 2);
            eRoot.SetElementValue("Test3", 3);
            //保存XML文件
            xdoc.Save("Test.xml");
        }

        /// <summary>
        /// 创建xml 方法二
        /// </summary>
        private static void CreateXML2()
        {
            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
            //声明xml版本
            XmlDeclaration xmldecl;
            xmldecl = xdoc.CreateXmlDeclaration("1.0", "gb2312", null);
            xdoc.AppendChild(xmldecl);

            //加入一个根节点
            XmlElement xmlelem = xdoc.CreateElement("Employee");
            xdoc.AppendChild(xmlelem);
            //加入另一个元素
            for (int i = 0; i < 3; i++)
            {
                XmlNode root = xdoc.SelectSingleNode("Employee");//查找<Employees> 
                XmlElement xe1 = xdoc.CreateElement("Node");//创建一个<Node>节点 
                xe1.SetAttribute("genre", "DouCube");//设置该节点genre属性 
                xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点ISBN属性 

                XmlElement xesub1 = xdoc.CreateElement("title");
                xesub1.InnerText = "CS从入门到精通";//设置文本节点 
                xe1.AppendChild(xesub1);//添加到<Node>节点中 
                XmlElement xesub2 = xdoc.CreateElement("author");
                xesub2.InnerText = "候捷";
                xe1.AppendChild(xesub2);
                XmlElement xesub3 = xdoc.CreateElement("price");
                xesub3.InnerText = "58.3";
                xe1.AppendChild(xesub3);

                root.AppendChild(xe1);//添加到<Employees>节点中
            }
            //保存创建好的XML文档
            xdoc.Save("data.xml"); 
        }
    }
}

  

posted @ 2016-11-04 17:12  BayMini  阅读(178)  评论(0编辑  收藏  举报