Unity3d: use C # script to generate and parse XML

  XML ( Extensible Markup Language ), Extensible Markup Language , a subset of the standard universal markup language, is a markup language used to mark electronic files to make them structural (this explanation comes from Baidu Encyclopedia).

  In Unity3d development, although XML is easy to redundant information, but its readability is strong, we usually write XML to store data.

  

  Use the C # script to create the XML file, directly add the code, and the comments are clearly written.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;   //首先引入命名空间
using System.IO;   //允许读写文件和数据流的类型以及提供基本文件和目录支持的类型

namespace XMLText
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xml = new XmlDocument();   //实例化xml对象

            //xml.AppendChild   /*添加指定节点到该节点的子节点末尾*/
            //xml.CreateXmlDeclaration   /*创建一个具有指定值的节点*/
            //("1.0", "UTF-8", "no"),Unity3d中可使用("1.0", "UTF-8", "null")   /*三个参数("版本","编码","是否依赖外部定义")*/
            xml.AppendChild(xml.CreateXmlDeclaration("1.0", "UTF-8", "no"));   //声明

            //xml.CreateElement   /*创建具有指定名称的元素*/
            xml.AppendChild(xml.CreateElement("root"));   //创建根节点

            //XmlNode   /*表示XML文档中的单个节点*/
            //xml.SelectSingleNode   /*选择匹配给定参数表达式的第一个XmlNode*/
            XmlNode root = xml.SelectSingleNode("root");   //获取根节点

            //XmlElement   /*表示一个元素*/
            XmlElement element = xml.CreateElement("node");   //添加元素

            element.SetAttribute("name", "value");   //设置具有指定名称的特性的值

            XmlElement childNode_1 = xml.CreateElement("child_1");   //在node节点下添加子节点
            childNode_1.SetAttribute("child_1", "first");   //给子节点添加属性
            XmlElement childNode_2 = xml.CreateElement("child_2");
            childNode_2.SetAttribute("child_2", "second");

            //逐层级添加节点
            element.AppendChild(childNode_1);
            element.AppendChild(childNode_2);
            root.AppendChild(element);

            xml.Save(@"C:\Users\dadahandsome\Desktop\myxml.xml");   //将xml保存至指定位置
                          				            //Unity3d中使用  Application.dataPath + "指定位置"   来保存xml
                          					    //Application.dataPath 为 Unity3d的 Assets文件夹目录 
        }
    }
}

  Results (using the Unity path is generated in the corresponding folder under Assets)

    

Published 16 original articles · praised 7 · 20,000+ views

Guess you like

Origin blog.csdn.net/yuecangjiao5151/article/details/76696495