xml 读写

前端之家收集整理的这篇文章主要介绍了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);
                }

            }

        }
    }
}
原文链接:https://www.f2er.com/xml/293702.html

猜你在找的XML相关文章