Unity uses C # to parse and update TXT, Json and XML files

It doesn't need to say much about the importance of reading configuration files for a game. This article summarizes the C # parsing text file method I often use recently. As a graffiti, this article is only used to provide a few ideas for solving problems, and does not consider whether the code is elegant or not.

preparation

Create a class to save single site information.

 public class Site   { public string Name{get; set;} public string Url{ get;  set;} }

Create a class to save the Site class array.

 public class SitesList { public Site[] sites; }

Create a script with a random name. Write the initialization path code in the Start method (the initial content mentioned below is this):

 //Application.dataPath, the attribute used to obtain the assets path in unity, is only used for example testing. string path = Application.dataPath + "/Resources/"; string jsonName = "Sites.json"; string txtName = "Sites.txt"; string xmlName = "Sites.xml"; string jsonPath = path + jsonName; string txtPath = path + txtName; string xmlPath = path + xmlName;

TXT file storage and parsing

TXT save

Idea: manually convert the class into a string, spell the string, and save it to a file. code:

 public void TxtToFile(SitesList sitesList,string filePath) { string str = "Name|Url" + '\n'; for (int i = 0;  i < sitesList.sites.Length; i++) { str += sitesList.sites[i]. Name + '|' + sitesList.sites[i]. Url  //The last line does not need additional line breaks +  (i == sitesList.sites.Length - 1 ? "": "\n"); } FileStream fs = File.Open (filePath, FileMode.Create); StreamWriter sw = new StreamWriter (fs); sw.Write (str); sw.Flush (); sw.Close (); fs.Close (); Debug.Log ("saved successfully"); }

The following contents are added to start:

 Site s1=new Site() {Name="Coming and going", Url=“ http://www.azimiao.com "}; Site s2 = new Site (){ Name = "Xema", Url = "https://" }; Site s3 = new Site (){ Name ="Pret",Url = "https://"}; SitesList siteList = new SitesList (); siteList.sites = new Site[]{ s1,s2,s3}; TxtToFile (siteList, txtPath);

Create a Cube (optional) in unity, mount the script to the game object, and click Run. The effect is as shown in the figure:

The contents of the saved file are:

 Name|Url Zimiao haunts| http://www.azimiao.com Xema|https:// Pret|https://

TXT reading and formatting

Idea: Read all contents in the file, cut the string according to the newline symbol ' n', and each element of the string array obtained is a Site object. Separate object strings according to identifiers ('|' is used here), create objects and assign values respectively. code:

 public void TxtToClass(out SitesList rec,string filePath) { rec = new SitesList (); if (! File.Exists(filePath)) { Debug.Log ("File does not exist"); return; } FileStream fs = File.Open (filePath, FileMode.Open); StreamReader sr = new StreamReader (fs); string txtData = sr.ReadToEnd (); //Cut each line string[] lineData = txtData. Split ('\n'); //Incontainer array initialization rec.sites = new Site[lineData. Length -1]; for (int i = 1;  i < lineData.Length; i++) { int index = 0; //Cut Element String string[] siteTemp = lineData [i]. Split ('|'); //Assign value to array in container rec.sites [i - 1] = new Site (){Name =siteTemp[index++],Url = siteTemp[index++] }; } }

The following content is added to start (the initial content is added, the same below):

 SitesList siteList = new SitesList (); TxtToClass (out siteList, txtPath); foreach (Site item in siteList.sites) { Debug.Log (item. Name + "|" + item.Url); }

Operation results:

TXT update

When there is no node in the txt file, there is no method to modify the local update of a node. Therefore, it is necessary to splice new strings to overwrite the original content. This is consistent with the saved content, so it is no longer repeated.

Storage and parsing of JSON files

Additional preparation: import required LitJSON.dll And reference its namespace:

 using LitJson;

JSON saving

Idea: First format the Site class as a Json string, then check whether the file exists (overwrite or create), and finally save the string. code:

 //Convert classes to Json objects public void SiteToJson(SitesList siteList,string filePath) { string jsonData = JsonMapper.ToJson (siteList); //It can not be written. The pen method will automatically process according to the parameters if (! File.Exists(filePath)) { //Create a new file if the file does not exist FileStream fstemp = File.Create (filePath); fstemp.Close (); Debug.Log ("File does not exist, new file has been created"); } //Open the file stream. Create mode means to create if it does not exist, and overwrite the original content if it exists FileStream fs = File.Open (filePath, FileMode.Create); //Create StreamWriter StreamWriter sw = new StreamWriter (fs, System.Text.Encoding.UTF8); sw.Write (jsonData); //Empty buffer and ensure writing sw.Flush (); //Close StreamWriter sw.Close (); //Close file stream fs.Close (); Debug.Log ("Write Complete"); }

The following content is added to start (the initial content is added, the same below):

 Site s1=new Site() {Name="Coming and going", Url=“ http://www.azimiao.com "}; Site s2 = new Site (){ Name = "Xema", Url = "https://" }; Site s3 = new Site (){ Name ="Pret",Url = "https://"}; siteList.sites = new Site[]{ s1,s2,s3}; SiteToJson (siteList, jsonPath);

Operation effect:

Open the created Json file, and find that the added content is (no line break in the original content, but manually added a line break for aesthetic purposes):

 { "sites": [ {"Name":"\u6893\u55B5\u51FA\u6CA1","Url":" http://www.azimiao.com "}, {"Name":"Xema","Url":"https://"}, {"Name":"Pret","Url":"https://"} ] }

JSON reading and formatting

Idea: First read all characters in the file, then convert them into Json strings, and finally parse them into objects. code:

 //Convert Json to class public void ParseXml(out SitesList rec,string filePath) { if (! File.Exists(filePath)) { Debug.LogWarning (filePath+"does not exist"); return; } //FileMode. Open, Open an existing file. If it does not exist, throw an exception FileStream fs = File.Open (filePath,FileMode.Open); StreamReader sr = new StreamReader (fs); string data = sr.ReadToEnd (); rec = JsonMapper.ToObject<SitesList> (data); //Close Stream sr.Close (); //Close Stream fs.Close (); Debug.Log ("Read Complete"); }

The following content is added to start (the initial content is added, the same below):

 SitesList siteList; ParseXml (out siteList, jsonPath); foreach (Site item in siteList.sites) { Debug.Log (item.Name+"|"+item.Url); }

Operation results:

to update

No, the reason is the same as TXT.

XML

Xml Meizizi Meizizi. Preparation: Reference namespace:

 using System.Xml;

Create an xml file containing the xml header and root node:

 <? xml version="1.0" encoding="UTF-8" ?> <Sites></Sites>

XML addition and saving

Idea: Get the xml root node, insert a child node into the xml root node, and then save it. code:

 public void ClassToXml(SitesList sitesList,string filePath) { XmlDocument doc = new XmlDocument (); //Load File doc.Load (filePath); //Get Root Node Sites XmlNode root = doc.SelectSingleNode ("Sites"); foreach (Site item in sitesList.sites) { XmlElement site = doc.CreateElement("Site"); XmlElement name = doc.CreateElement ("Name"); name.InnerText = item.Name; XmlElement url = doc.CreateElement ("Url"); url.InnerText = item.Url; //Add Child Node site.AppendChild (name); site.AppendChild (url); root.AppendChild (site); } //Save File doc.Save (filePath); }

The following content is added to start (the initial content is added, the same below):

 Site s1=new Site() {Name="Coming and going", Url=“ http://www.azimiao.com "}; Site s2 = new Site (){ Name = "Xema", Url = "https://" };  Site s3 = new Site (){ Name ="Pret",Url = "https://"}; SitesList siteList = new SitesList (); siteList.sites = new Site[]{ s1,s2,s3}; ClassToXml(siteList,xmlPath);

Running result: Open the original xml and you can see the following additions:

XML reading and parsing

Idea: Get the root node Sites, cycle through the root node to get each child node Site, and create objects through the Name node in Site and the innerText of the Url node. code:

 public void XmlToClass(out SitesList rec, string filePath) { XmlDocument doc = new XmlDocument (); doc.Load (filePath); XmlNode root = doc.SelectSingleNode ("Sites"); XmlNodeList xmlSites = root.SelectNodes ("Site"); rec = new SitesList (); rec.sites = new Site[xmlSites. Count]; int index = 0; foreach (XmlNode item in xmlSites) { string name = item ["Name"]. InnerText; string url = item ["Url"]. InnerText; Site temp = new Site (){ Name = name, Url = url }; rec.sites [index] = temp; index++; }

Add the following content to Start:

 SitesList siteList = new SitesList (); XmlToClass (out siteList, xmlPath); foreach (Site item in siteList.sites) { Debug.Log (item. Name + "|" + item.Url); }

Operation result: as shown in the figure below:

XML Update

Idea: Get the node object through the condition statement, modify the value of innerText, and then save it. This can be achieved by slightly modifying the above.

XML deletes a node

Use doc RemoveChild (XmlNode oldNode).

summary

Compared with TXT and JSON, XML is easier to implement local updates. Through these small examples, you can master simple file reading and writing, that is, file serialization and deserialization methods.

References

  1. [Header] [Unity] Unity Japan UnityChanSD Role
Zimiao haunting blog (azimiao. com) All rights reserved. Please note the link when reprinting: https://www.azimiao.com/2533.html
Welcome to the Zimiao haunting blog exchange group: three hundred and thirteen million seven hundred and thirty-two thousand

Comment

*

*

Comment area

  1. How can the email notification plug-in of emmm big boss fail to send all the time?

  2. answer 10-19 10:19 reply

    Barking~Add a friend chain~
    answer:www.traceback.cc

  3. c0smxsec 10-22 15:49 reply

    Your old driver plays games