C#存取XML文件

XML文件是一种常用的文件格式,例如WinForm里面的app.config以及Web程序中的web.config文件,还有许多重要的场所都有它的身影。Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具。XML是一种简单的数据存储语言,使用一系列简单的标记描述数据,而这些标记可以用方便的方式建立,虽然XML占用的空间比二进制数据要占用更多的空间,但XML极其简单易于掌握和使用。微软也提供了一系列类库来倒帮助我们在应用程序中存储XML文件。

“在程序中访问进而操作XML文件一般有两种模型,分别是使用DOM(文档对象模型)和流模型,使用DOM的好处在于它允许编辑和更新XML文档,可以随机访问文档中的数据,可以使用XPath查询,但是,DOM的缺点在于它需要一次性的加载整个文档到内存中,对于大型的文档,这会造成资源问题。流模型很好的解决了这个问题,因为它对XML文件的访问采用的是流的概念,也就是说,任何时候在内存中只有当前节点,但它也有它的不足,它是只读的,仅向前的,不能在文档中执行向后导航操作。”

常用的方式有:
1. 使用XmlDocument
2. 使用XmlTextReader
3. 使用Linq to XML
4. 使用序列化

这里尝试使用1,3,4来测试,

生成的XML格式如下:

<NBA>
  <selected>Kobe Bryantselected>
  <player name="Kobe Bryant" birth="1978" team="Laker" position="shooting guard">
    <NBAchampion>5NBAchampion>
    <NBAFinalsMVP>2NBAFinalsMVP>
    <AllStar>18AllStar>
    <number>8,24number>
  player>
  <player name="LeBron James" birth="1984" team="Cavaliers" position="small forward">
    <NBAchampion>3NBAchampion>
    <NBAFinalsMVP>3NBAFinalsMVP>
    <AllStar>13AllStar>
    <number>23number>
  player>
NBA>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;//Linq to XML

namespace XML
{
    class Program
    {
        static void Main(string[] args)
        {
            generateXMLFile(Path.Combine(baskteball.directory, "NBA.xml"));

            baskteball.init();
            Console.WriteLine(baskteball.player);

            getXMLInformation(Path.Combine(baskteball.directory, "NBA.xml"));

            getXMLInformationByLINQ(Path.Combine(baskteball.directory, "NBA.xml"));

            Console.ReadKey();
        }

        private static void generateXMLFile(string saveFilePath)
        {
            XmlDocument xmldoc = new XmlDocument();
            //declaire
            XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
            //root 
            XmlElement xmlelement = xmldoc.CreateElement("NBA");
            xmldoc.AppendChild(xmlelement);
            //first level node
            XmlElement selectedName = xmldoc.CreateElement("selected");
            selectedName.InnerText = "Kobe Bryant";
            xmlelement.AppendChild(selectedName);
            //first level node
            XmlElement player = xmldoc.CreateElement("player");
            player.SetAttribute("name", "Kobe Bryant");
            player.SetAttribute("birth", "1978");
            player.SetAttribute("team", "Laker");
            player.SetAttribute("position", "shooting guard");
            //second level node
            XmlElement championEle = xmldoc.CreateElement("NBAchampion");
            championEle.InnerText = "5";
            player.AppendChild(championEle);

            XmlElement MVPEle = xmldoc.CreateElement("NBAFinalsMVP");
            MVPEle.InnerText = "2";
            player.AppendChild(MVPEle);

            XmlElement AllStarEle = xmldoc.CreateElement("AllStar");
            AllStarEle.InnerText = "18";
            player.AppendChild(AllStarEle);

            XmlElement numberEle = xmldoc.CreateElement("number");
            numberEle.InnerText = "8,24";
            player.AppendChild(numberEle);

            xmlelement.AppendChild(player);

            player = xmldoc.CreateElement("player");
            player.SetAttribute("name", "LeBron James");
            player.SetAttribute("birth", "1984");
            player.SetAttribute("team", "Cavaliers");
            player.SetAttribute("position", "small forward");

            championEle = xmldoc.CreateElement("NBAchampion");
            championEle.InnerText = "3";
            player.AppendChild(championEle);

            MVPEle = xmldoc.CreateElement("NBAFinalsMVP");
            MVPEle.InnerText = "3";
            player.AppendChild(MVPEle);

            AllStarEle = xmldoc.CreateElement("AllStar");
            AllStarEle.InnerText = "13";
            player.AppendChild(AllStarEle);

            numberEle = xmldoc.CreateElement("number");
            numberEle.InnerText = "23";
            player.AppendChild(numberEle);

            xmlelement.AppendChild(player);

            xmldoc.Save(saveFilePath);
        }

        private static void getXMLInformation(string xmlFilelPath)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilelPath);
            //fetch the root
            XmlNode node = doc.SelectSingleNode("NBA");

            Console.WriteLine("<{0}>", node.Name);
            //fetch the first level node
            foreach (XmlElement element in node)
            {
                Console.WriteLine("  <{0}>", element.Name);
                //Console.WriteLine(element.NodeType);

                XmlNodeList grandsonNd = element.ChildNodes;
                //fetch the second level node
                foreach (XmlNode nd in grandsonNd)
                {
                    string name, innerText;
                    if (nd.NodeType == XmlNodeType.Text)
                    {
                        name = nd.ParentNode.Name;
                        innerText = nd.InnerText;
                        Console.WriteLine("  {0}", innerText);

                    }
                    else
                    {
                        name = nd.Name;
                        innerText = nd.InnerText;
                        Console.WriteLine("    <{0}>{1}", name, innerText);
                    }
                }
                Console.WriteLine("  ", element.Name);
            }
            Console.WriteLine("", node.Name);
        }

        private static void getXMLInformationByLINQ(string xmlFilelPath)
        {
            XElement xe = XElement.Load(xmlFilelPath);
            IEnumerable element = from e in xe.Elements("player") where e.Attribute("name").Value == "Kobe Bryant" select e;
            foreach (XElement player in element)
            {
                Console.WriteLine(player.ToString());
                Console.WriteLine(player.Element("number").Value);
            }
        }
    }

    public class baskteball
    {
        public static NBAPlayer player { set; get; }
        public static string directory { get { return AppDomain.CurrentDomain.BaseDirectory; } }
        public static void init()
        {
            XmlSerializer xml = new XmlSerializer(typeof(NBA));
            NBA _all;
            string file = Path.Combine(directory, "NBA.xml");
            using (TextReader reader = new StreamReader(file))
            {
                _all = (NBA)xml.Deserialize(reader);

            }
            if (_all == null || _all.nbaplayer == null || _all.nbaplayer.Length == 0)
            {
                throw new Exception("no player avaliable.");
            }
            foreach (NBAPlayer nbaplayer in _all.nbaplayer)
            {
                if (_all.selected == nbaplayer.name)
                {
                    player = nbaplayer;
                    if (_all.selected == "Kobe Bryant")
                        player.retirement = true;
                    return;
                }
            }
        }
    }

    [Serializable]
    public class NBA
    {
        public string selected { set; get; }
        [XmlElement("player")]
        public NBAPlayer[] nbaplayer;
    }

    [Serializable]
    public class NBAPlayer
    {
        [XmlAttribute]
        public string name;
        public int NBAchampion { set; get; }
        public int NBAFinalsMVP { set; get; }
        public int AllStar { set; get; }
        public string number { set; get; }
        [XmlIgnore]
        public bool retirement { set; get; }
        public override string ToString()
        {
            //return base.ToString();
            return String.Format("{4} gets {0} times NBAchampion, {1} times NBAFinalsMVP, {2} times AllStar, number is {3}. {5}", NBAchampion, NBAFinalsMVP, AllStar, number, name, retirement == true ? "He retired." : "");
        }
    }

}

XML简介及两种C#读取方式
c#读取XML
C# XML文件的一些操作(XmlDocument、XmlElement、XmlNode)

你可能感兴趣的:(XML,C#,XML,LINQ-XML,Serialize)