C# : 读取简单的XML文件

来源:互联网 发布:java桌面开发框架 编辑:程序博客网 时间:2024/04/30 18:39

ServerConfig.xml

<root><Server><IP>127.0.0.1</IP><port>8080</port></Server></root>
XmlTest.cs


using System;using System.Collections.Generic;using System.IO;using System.Text;using System.Xml;namespace XmlTest{    public class XmlReader    {        static void Main()        {            string xmlFile = "ServerConfig.xml";            XmlDocument xmlDoc = new XmlDocument();            string xPath = "/root/Server";            try            {                xmlDoc.Load(xmlFile);                XmlNode aNode = xmlDoc.SelectSingleNode(xPath);                if (aNode != null)                {                    Console.WriteLine(aNode.OuterXml);                }                xPath = "/root/Server/IP";                XmlElement elem = xmlDoc.SelectSingleNode(xPath) as XmlElement;                if (elem != null)                {                    Console.WriteLine(elem.OuterXml);                    Console.WriteLine(elem.InnerText);                    Console.WriteLine(elem.Value);                }                xPath = "/root/Server/port";                elem = xmlDoc.SelectSingleNode(xPath) as XmlElement;                if (elem != null)                {                    Console.WriteLine(elem.OuterXml);                    int port = int.Parse(elem.InnerText);                    Console.WriteLine(port.ToString());                }            }            catch (Exception ex)            {                Console.WriteLine(ex.ToString());            }        }    }}


0 0
原创粉丝点击