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

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

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

1、生成XML

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

运行结果

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

2.更新XML文件

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

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

运行结果

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

3.添加XML

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

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

运行结果

 
1
2
3
4
5
6
7
8
9
10
11
12
<transforms>
  <rotation id="1000" name="momo">
    <x>0</x>
    <y>1</y>
    <z id="1">update00000</z>
  </rotation>
  <rotation id="1" name="yusong">
    <x id="1">0</x>
    <y>1</y>
    <z>2</z>
  </rotation>
</transforms>

4.删除XML

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

运行结果

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<transforms>
  <rotation id="1000" name="momo">
    <x>0</x>
    <y>1</y>
    <z>
    </z>
  </rotation>
  <rotation name="yusong">
    <x id="1">0</x>
    <y>1</y>
    <z>
    </z>
  </rotation>
</transforms>

4.解析与输出上面的XML

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

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

接着是处理JSON

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

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

运行结果

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

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

运行结果

(转载)Unity3D研究院之使用 C#合成解析XML与JSON(四十一)的更多相关文章

  1. C#合成解析XML与JSON

      http://www.xuanyusong.com/archives/1901  XML与JSON在开发中非常重要, 其实核心就是处理字符串.一个是XML的字符串一个是JSON的字符串,尤其是在处 ...

  2. boost-使用property_tree来解析xml、json

    property_tree是一个保存了多个属性值的树形数据结构,可以用来解析xml.json.ini.info文件.要使用property_tree和xml解析组件的话需要包含"boost/ ...

  3. Python解析xml与JSON

    xml与json是常用的文件交换格式,常用来表示网页的html则是xml的变种.解析xml和json在web开发中有着重要应用. DOM解析XML 文件对象模型(Document Object Mod ...

  4. ios解析XML和json数据

    解析的基本概念所谓“解析”:从事先规定好的格式串中提取数据解析的前提:提前约定好格式.数据提供方按照格式提供数据.数据获取方按照格式获取数据iOS开发常见的解析:XML解析.JSON解析 一.XML数 ...

  5. 解析xml文件的四种方式

    什么是 XML? XML 指可扩展标记语言(EXtensible Markup Language) XML 是一种标记语言,很类似 HTML XML 的设计宗旨是传输数据,而非显示数据 XML 标签没 ...

  6. IOS 请求数据解析 XML 和 JSON

    好久没写文章了,回忆一下以前的内容记录一下吧. 这一段主要接触的就是数据解析,就说一下数据解析 现在数据解析一般解析两种数据 xml 和 JSON 那就从xml解析说起吧 xml解析需要用到一个类 N ...

  7. android基础篇------------java基础(11)(文件解析xml and Json )

    一:xml文件解析 首先看一下:我们要解析的内容: <?xml version="1.0" encoding="gbk" ?> - <book ...

  8. UI:数据的解析XML与JSON

    XML  和  JSON 语言  本篇博客来自互联网参考 XML 和 JSON 的互相转化 有属性的转化为对象,无属性的转化为字符串 节点的顺序性不可逆,XML有顺序,JSON 无顺序 XML 和 J ...

  9. Unity3D研究院之Machine动画脚本自动生成AnimatorController(七十一)

    以前的项目一直不敢用Machine动画,因为当时立项的时候Machine动画还不成熟,最近项目做得差不多了我能有点时间学习,我就想在研究学习学习Machine.用Machine动画的时候需要创建一个A ...

随机推荐

  1. 十个Chatbot框架介绍

    十个Chatbot框架介绍 原创 2016年12月13日 16:01:23 4616 Chatbot列表 1.  Artificial Intelligence Markup Language    ...

  2. CAP 定理的含义

    分布式系统(distributed system)正变得越来越重要,大型网站几乎都是分布式的. 分布式系统的最大难点,就是各个节点的状态如何同步.CAP 定理是这方面的基本定理,也是理解分布式系统的起 ...

  3. linux/mac系统的软链接文件与硬链接文件

    1.硬连接只能使用在文件上,不可以使用在文件夹上.至于文件前面的硬链接数字的含义如下: 如图标注区,为硬连接的数量,文件前的数字1表示没有硬链接.文件夹前面的数字至少是2,含义是这个文件夹是空文件夹, ...

  4. iOS:实现图片的无限轮播

    为尊重原创,特注明原文链接:http://m.myexception.cn/operating-system/1949043.html 图片轮播及其无限循环效果 平时APP中的广告位或者滚动的新闻图片 ...

  5. [Python爬虫] 之十九:Selenium +phantomjs 利用 pyquery抓取超级TV网数据

    一.介绍 本例子用Selenium +phantomjs爬取超级TV(http://www.chaojitv.com/news/index.html)的资讯信息,输入给定关键字抓取资讯信息. 给定关键 ...

  6. 使用IntelliJ IDEA创建Maven多模块项目

    转载:http://blog.csdn.net/xyw591238/article/details/52794788 使用Maven管理项目时,往往需要创建多个模块,模块之间存在相互引用的关系.对于M ...

  7. perl学习笔记——哈希

    哈希 哈希是一种数据结构,它和数组的相似之处在于可以容难任意多的值并能按需取用,而他和数组的不同在于索引的方式,数组是以数字为索引而哈希则是以名字为索引. 哈希的键是唯一的,哈希的值可以重复. 哈希的 ...

  8. .Net之路(十五)图解LoadRunner压力測试

    在项目编码阶段结束后,就须要进行软件測试. 成为软件开发过程中一个不可缺少的环节.而自己主动化測试也是将逐步取代人工繁杂的測试.压力測试就是软件測试对软件性能评估的一个方面,以下就简介我在使用load ...

  9. python基础 实战作业 ---Excel基本读写与数据处理

    代码地址如下:http://www.demodashi.com/demo/11650.html 看完本篇需要: 10min 作业练习需要: 0.5h~3h(依练习者对python熟悉程度而定) 看完本 ...

  10. select/poll/epoll原理探究及总结

    select,poll,epoll都是IO多路复用的机制.I/O多路复用就通过一种机制,可以监视多个描述符,一旦某个描述符就绪(一般是读就绪或者写就绪),能够通知程序进行相应的读写操作.但select ...