• Unity3D研究院之使用 C#合成解析XML与JSON


     XML与JSON在开发中非常重要, 其实核心就是处理字符串。一个是XML的字符串一个是JSON的字符串,尤其是在处理网络请求的时候,肯定是要用的。另外现在JSON非常的流行,我写了一个简单的例子融合了XML与JSON的合成与解析,希望大家喜欢!

    首先注意头文件,LitJson是处理JSON的第三方库,最后我会给出下载地址。

    1 using UnityEngine;
    2 using System.Collections;
    3 using System.Collections.Generic;
    4 using System.Xml;
    5 using System.IO;
    6 using System.Text;
    7 using LitJson;

    1、生成XML

    01 public void createXml()
    02 {
    03            //xml保存的路径,这里放在Assets路径 注意路径。
    04     string filepath = Application.dataPath + @"/my.xml";
    05            //继续判断当前路径下是否有该文件
    06     if(!File.Exists (filepath))
    07     {
    08                      //创建XML文档实例
    09          XmlDocument xmlDoc = new XmlDocument();
    10                      //创建root节点,也就是最上一层节点
    11          XmlElement root = xmlDoc.CreateElement("transforms");
    12                       //继续创建下一层节点
    13          XmlElement elmNew = xmlDoc.CreateElement("rotation");
    14                     //设置节点的两个属性 ID 和 NAME
    15          elmNew.SetAttribute("id","0");
    16          elmNew.SetAttribute("name","momo");
    17            //继续创建下一层节点
    18              XmlElement rotation_X = xmlDoc.CreateElement("x");
    19                  //设置节点中的数值
    20                  rotation_X.InnerText = "0";
    21                 XmlElement rotation_Y = xmlDoc.CreateElement("y");
    22                 rotation_Y.InnerText = "1";
    23                 XmlElement rotation_Z = xmlDoc.CreateElement("z");
    24                  rotation_Z.InnerText = "2";
    25                 //这里在添加一个节点属性,用来区分。。
    26        rotation_Z.SetAttribute("id","1");
    27  
    28          //把节点一层一层的添加至XMLDoc中 ,请仔细看它们之间的先后顺序,这将是生成XML文件的顺序
    29          elmNew.AppendChild(rotation_X);
    30          elmNew.AppendChild(rotation_Y);
    31          elmNew.AppendChild(rotation_Z);
    32      root.AppendChild(elmNew);
    33          xmlDoc.AppendChild(root);
    34          //把XML文件保存至本地
    35          xmlDoc.Save(filepath);
    36          Debug.Log("createXml OK!");
    37     }
    38 }

    运行结果

    1 <transforms>
    2   <rotation id="0" name="momo">
    3     <x>0</x>
    4     <y>1</y>
    5     <z id="1">2</z>
    6   </rotation>
    7 </transforms>

    2.更新XML文件

    以其中某个节点名称做条件,当查询到时更新该节点

    01 public void UpdateXml()
    02 {
    03     string filepath = Application.dataPath + @"/my.xml";
    04     if(File.Exists (filepath))
    05     {
    06          XmlDocument xmlDoc = new XmlDocument();
    07                      //根据路径将XML读取出来
    08          xmlDoc.Load(filepath);
    09                      //得到transforms下的所有子节点
    10          XmlNodeList nodeList=xmlDoc.SelectSingleNode("transforms").ChildNodes;
    11                      //遍历所有子节点
    12          foreach(XmlElement xe in nodeList)
    13          {
    14                             //拿到节点中属性ID =0的节点
    15             if(xe.GetAttribute("id")=="0")
    16             {
    17                                     //更新节点属性
    18                 xe.SetAttribute("id","1000");
    19                                     //继续遍历
    20                 foreach(XmlElement x1 in xe.ChildNodes)
    21                 {
    22                     if(x1.Name=="z")
    23                     {
    24                                                     //这里是修改节点名称对应的数值,而上面的拿到节点连带的属性。。。
    25                          x1.InnerText="update00000";
    26                     }
    27  
    28                 }
    29                 break;
    30             }
    31          }
    32          xmlDoc.Save(filepath);
    33          Debug.Log("UpdateXml OK!");
    34     }
    35  
    36 }

    运行结果

    1 <transforms>
    2   <rotation id="1000" name="momo">
    3     <x>0</x>
    4     <y>1</y>
    5     <z id="1">update00000</z>
    6   </rotation>
    7 </transforms>

    3.添加XML

    重复的地方我就不解释拉。

    01 public void AddXml()
    02 {
    03     string filepath = Application.dataPath + @"/my.xml";
    04     if(File.Exists (filepath))
    05     {
    06         XmlDocument xmlDoc = new XmlDocument();
    07         xmlDoc.Load(filepath);
    08         XmlNode root = xmlDoc.SelectSingleNode("transforms");
    09         XmlElement elmNew = xmlDoc.CreateElement("rotation");
    10         elmNew.SetAttribute("id","1");
    11         elmNew.SetAttribute("name","yusong");
    12  
    13          XmlElement rotation_X = xmlDoc.CreateElement("x");
    14          rotation_X.InnerText = "0";
    15          rotation_X.SetAttribute("id","1");
    16          XmlElement rotation_Y = xmlDoc.CreateElement("y");
    17          rotation_Y.InnerText = "1";
    18          XmlElement rotation_Z = xmlDoc.CreateElement("z");
    19          rotation_Z.InnerText = "2";
    20  
    21          elmNew.AppendChild(rotation_X);
    22          elmNew.AppendChild(rotation_Y);
    23          elmNew.AppendChild(rotation_Z);
    24          root.AppendChild(elmNew);
    25          xmlDoc.AppendChild(root);
    26          xmlDoc.Save(filepath);
    27          Debug.Log("AddXml OK!");
    28     }
    29 }

    运行结果

    01 <transforms>
    02   <rotation id="1000" name="momo">
    03     <x>0</x>
    04     <y>1</y>
    05     <z id="1">update00000</z>
    06   </rotation>
    07   <rotation id="1" name="yusong">
    08     <x id="1">0</x>
    09     <y>1</y>
    10     <z>2</z>
    11   </rotation>
    12 </transforms>

    4.删除XML

    01 public void deleteXml()
    02 {
    03     string filepath = Application.dataPath + @"/my.xml";
    04     if(File.Exists (filepath))
    05     {
    06          XmlDocument xmlDoc = new XmlDocument();
    07          xmlDoc.Load(filepath);
    08          XmlNodeList nodeList=xmlDoc.SelectSingleNode("transforms").ChildNodes;
    09          foreach(XmlElement xe in nodeList)
    10          {
    11             if(xe.GetAttribute("id")=="1")
    12             {
    13                 xe.RemoveAttribute("id");
    14             }
    15  
    16             foreach(XmlElement x1 in xe.ChildNodes)
    17             {
    18                 if(x1.Name == "z")
    19                 {
    20                     x1.RemoveAll();
    21  
    22                 }
    23             }
    24          }
    25          xmlDoc.Save(filepath);
    26          Debug.Log("deleteXml OK!");
    27     }
    28  
    29 }

    运行结果

    01 <transforms>
    02   <rotation id="1000" name="momo">
    03     <x>0</x>
    04     <y>1</y>
    05     <z>
    06     </z>
    07   </rotation>
    08   <rotation name="yusong">
    09     <x id="1">0</x>
    10     <y>1</y>
    11     <z>
    12     </z>
    13   </rotation>
    14 </transforms>

    4.解析与输出上面的XML

    01 public void showXml()
    02 {
    03     string filepath = Application.dataPath + @"/my.xml";
    04     if(File.Exists (filepath))
    05     {
    06          XmlDocument xmlDoc = new XmlDocument();
    07          xmlDoc.Load(filepath);
    08          XmlNodeList nodeList=xmlDoc.SelectSingleNode("transforms").ChildNodes;
    09         //遍历每一个节点,拿节点的属性以及节点的内容
    10          foreach(XmlElement xe in nodeList)
    11          {
    12             Debug.Log("Attribute :" + xe.GetAttribute("name"));
    13             Debug.Log("NAME :" + xe.Name);
    14             foreach(XmlElement x1 in xe.ChildNodes)
    15             {
    16                 if(x1.Name == "y")
    17                 {
    18                     Debug.Log("VALUE :" + x1.InnerText);
    19  
    20                 }
    21             }
    22          }
    23          Debug.Log("all = " + xmlDoc.OuterXml);
    24  
    25     }
    26 }

    运行结果(点击图片最大化)

    接着是处理JSON

    5.解析JSON字符串显示字典键值

    01 public void ResolveJson()
    02 {
    03              //定义的JSON字符串,注意JSON的格式
    04      string str = @"
    05         {
    06             ""Name""     : ""yusong"",
    07             ""Age""      : 26,
    08             ""Birthday"" : ""1986-11-21"",
    09             ""Thumbnail"":[
    10             {
    11                 ""Url"":    ""http://xuanyusong.com"",
    12                 ""Height"": 256,
    13                 ""Width"":  ""200""
    14             },
    15             {
    16                 ""Url"":    ""http://baidu.com"",
    17                 ""Height"": 1024,
    18                 ""Width"":  ""500""
    19             }
    20  
    21             ]
    22         }";
    23     //这里是解析,包括整形与字符串
    24     JsonData jd = JsonMapper.ToObject(str);
    25     Debug.Log("name = " + (string)jd["Name"]);
    26     Debug.Log("Age = " + (int)jd["Age"]);
    27     Debug.Log("Birthday = " + (string)jd["Birthday"]);
    28     JsonData jdItems = jd["Thumbnail"];
    29  
    30     for (int i = 0; i < jdItems.Count; i++)
    31     {
    32         Debug.Log("URL = " + jdItems[i]["Url"]);
    33         Debug.Log("Height = " + (int)jdItems[i]["Height"]);
    34         Debug.Log("Width = " + jdItems[i]["Width"]);
    35     }
    36 }

    运行结果

    6.合成JSON字符串,先合成 然后在输出。

    01 public void MergerJson()
    02 {
    03     StringBuilder sb = new StringBuilder ();
    04     JsonWriter writer = new JsonWriter (sb);
    05  
    06     writer.WriteObjectStart ();
    07  
    08     writer.WritePropertyName ("Name");
    09     writer.Write ("yusong");
    10  
    11     writer.WritePropertyName ("Age");
    12     writer.Write (26);
    13  
    14     writer.WritePropertyName ("Girl");
    15  
    16     writer.WriteArrayStart ();
    17  
    18     writer.WriteObjectStart();
    19     writer.WritePropertyName("name");
    20     writer.Write("ruoruo");
    21     writer.WritePropertyName("age");
    22     writer.Write(24);
    23     writer.WriteObjectEnd ();
    24  
    25     writer.WriteObjectStart();
    26     writer.WritePropertyName("name");
    27     writer.Write("momo");
    28     writer.WritePropertyName("age");
    29     writer.Write(26);
    30     writer.WriteObjectEnd ();
    31  
    32     writer.WriteArrayEnd();
    33  
    34     writer.WriteObjectEnd ();
    35     Debug.Log(sb.ToString ());
    36  
    37     JsonData jd = JsonMapper.ToObject(sb.ToString ());
    38     Debug.Log("name = " + (string)jd["Name"]);
    39     Debug.Log("Age = " + (int)jd["Age"]);
    40     JsonData jdItems = jd["Girl"];
    41     for (int i = 0; i < jdItems.Count; i++)
    42     {
    43         Debug.Log("Girl name = " + jdItems[i]["name"]);
    44         Debug.Log("Girl age = " + (int)jdItems[i]["age"]);
    45     }
    46 }

    运行结果

    工程下载: http://vdisk.weibo.com/s/jkBml

  • 相关阅读:
    springMVC-MyBatis-Mysql 环境下, 返回时间格式不是指定格式
    大话设计模式--第一章 简单工厂设计模式
    java编程思想第四版第十八章总结
    尚学堂-马士兵-专题-正则表达式
    张孝祥java高新技术 --- jkd1.5 新特性 -- 精华总结
    Python—文件进阶操作
    Python—文件读写操作
    Python—异常处理
    Python—网络抓包与解包(pcap、dpkt)
    Python—其它模块
  • 原文地址:https://www.cnblogs.com/bluesea-flash/p/3412899.html
Copyright © 2020-2023  润新知