xml 读写

该内容在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);
                }

            }

        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值