加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml 读写

发布时间:2020-12-16 08:09:25 所属栏目:百科 来源:网络整理
导读:该内容在C#控制台完成 平台为:Mac 测试时记得修改路径。 using System;using System.Xml;namespace WriteAndReadXml{ class MainClass { static string path = @"/Users/gaolili/Desktop/TestFile/date.xml"; public static void Main(string[] args) { Wri

该内容在C#控制台完成

平台为:Mac

测试时记得修改路径。

using System;
using System.Xml;
namespace WriteAndReadXml
{
    class MainClass
    {
        static string path = @"/Users/gaolili/Desktop/TestFile/date.xml";
        public static void Main(string[] args)
        {
            WriteXml();
            ReadXml();
            Console.WriteLine("Hello World!");
        }
        //写入xml
        static void WriteXml(){
            //创建xml对象
            XmlDocument xmd = new XmlDocument();
            //定义xml文档元素
            XmlElement xmlEle;
            //定义xml申明段落
            XmlDeclaration xmlDec;
            xmlDec = xmd.CreateXmlDeclaration("1.0","UTF-8",null);
            //把该段落写入xml文档中
            xmd.AppendChild(xmlDec);
            //加入一个根元素
            xmlEle = xmd.CreateElement("","Employees","");
            xmd.AppendChild(xmlEle);
            for (int i = 0; i < 3; i++)
            {
                XmlNode root = xmd.SelectSingleNode("Employees");
                XmlElement xel = xmd.CreateElement("Node");
                xel.SetAttribute("genre","DouCube");
                xel.SetAttribute("ISBN","2-3-4");
                xel.SetAttribute("name","Gao");
                XmlElement xesub1 = xmd.CreateElement("title");
                xesub1.InnerText = "U3D Super";
                xel.AppendChild(xesub1);
                XmlElement xesub2 = xmd.CreateElement("author");
                xesub2.InnerText = "GaoJin";
                xel.AppendChild(xesub2);
                XmlElement xesub3 = xmd.CreateElement("price");
                xesub3.InnerText = (20+i).ToString();
                xel.AppendChild(xesub3);
                root.AppendChild(xel);
            }
            //Save
            xmd.Save(path);
        }
        //读取xml
        static void ReadXml(){
            XmlDocument xmd = new XmlDocument();
            //加载路径
            xmd.Load(path);
            //获取根节点
            XmlNode xn = xmd.SelectSingleNode("Employees");
            XmlNodeList xnl = xn.ChildNodes;
            for (int i = 0; i < xnl.Count; i++)
            {
                Console.WriteLine( xnl[i].Attributes.Item(i).Name);
                Console.WriteLine(xnl[i].Name);
                Console.WriteLine(xnl[i].InnerText);
                for (int j = 0; j < xnl[i].ChildNodes.Count; j++)
                {
                    Console.WriteLine(" child node  InnerText :   "+xnl[i].ChildNodes.Item(j).InnerText);
                }

            }

        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读