Unity3dC XML语言
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
代码
[csharp]view plaincopyprint?
ing UnityEngine;
ing System.IO;
ing System.Xml;
ing System.Collections;
5.
6.public class XMLTest : MonoBehaviour {
7.
8.private string _xmlPath;
9.private string _userId = "";
10.private string _userName = "";
11.
12.
13.
14.// Use this for initialization
15.void Start ()
16. {
17.//xml路径
18. _xmlPath = Application.dataPath + "/test.xml";
19. CreatXML();
20. }
21.
22.// Update is called once per frame
23.void Update ()
24. {
25.
26. }
27.
28.void CreatXML()
29. {
30.//检测xml是否存在
31.if (!File.Exists(_xmlPath))
32. {
33.//新建xml实例
34. XmlDocument xmlDoc = new XmlDocument();
35.//创建根节点,最上层节点
36. XmlElement data = xmlDoc.CreateElement("data");
37. xmlDoc.AppendChild(data);
38.//二级节点
39. XmlElement user = xmlDoc.CreateElement("user");
40. data.AppendChild(user);
41.//二级节点的两个属性
42. XmlElement userId = xmlDoc.CreateElement("userId");
43. user.AppendChild(userId);
44. XmlElement userName = xmlDoc.CreateElement("userName");
45. user.AppendChild(userName);
46.
47.//将xml文件保存到本地
48. xmlDoc.Save(_xmlPath);
49. Debug.Log("xml creat success!");
50. }
51. }
52.
53.void OnGUI()
54. {
55. GUI.Button(new Rect(0, 0, 100, 50), "UserId");
56.
57. _userId = GUI.TextField(new Rect(100, 0, 100, 50), _userId);
58.
59.
60. GUI.Button(new Rect(0, 50, 100, 50), "UserName");
61.
62.
63. _userName = GUI.TextField(new Rect(100, 50, 100, 50), _userName);
64.if(GUI.Button(new Rect(200,25,100,50),"更改"))
65. {
66. UpdateXml(_userId, _userName);
67. }
68.
69.
70.//GUI.Button(new Rect(0, 100, 150, 50), "UserId" + _userId);
71.//GUI.Button(new Rect(0, 150, 150, 50), "UserName" + _userName);
72.
73.
74. }
75.
76.void UpdateXml(string userId,string userName)
77. {
78.if (File.Exists(_xmlPath))
79. {
80. XmlDocument xmlDoc = new XmlDocument();
81. xmlDoc.Load(_xmlPath);
82. XmlNodeList nodeList = xmlDoc.SelectSingleNode("data/user").Chil
dNodes;
83.foreach (XmlElement xe in nodeList)
84. {
85. Debug.Log(nodeList.Count);
86.if ( == "userId")
87. {
88. xe.InnerText = userId;
89. Debug.Log("edit");
90.
91. }
92.if ( == "userName")
93. {
94. xe.InnerText = userName;
95.break;
96. }
97. }
98. xmlDoc.Save(_xmlPath);
99. }
100. }
101.}