Unity study notes–data persistence XML file (1)
XML related
Xml is Extensible Markup Language, a file format. We use xml to complete the persistent storage of data. After we wait for a program to finish running, save the data in the memory (saved on the hard disk/server) to achieve persistent storage of the data.
Reading, saving and modifying xml files
Key points:
-
Loading of XML files
-
Search and access XML file nodes
-
Reading the content of XML file nodes (InnerText or Attributes[“id”].Value form access)
There are detailed comments in the code! Available for reference and comparison learning!
using System.IO;
using System.Xml;
using UnityEngine;
namespace Building.XML
{
public class LoadXMLFile:MonoBehaviour
{
private void Start()
{
//Get xml file
XmlDocument xmlFile = new XmlDocument();
//Load the text format and parse it into xml form for acquisition.
//TextAsset textAsset = Resources.Load("Text");
// xmlFile.LoadXml(textAsset.text);
//Load via path
xmlFile.Load(Application.streamingAssetsPath+"/Text.xml");
//Read nodes in xml
XmlNode root = xmlFile.SelectSingleNode("PlayerInfo");
XmlNode nodeName = root.SelectSingleNode("Name");
XmlNode nodeList = root.SelectSingleNode("Item");
//Get the data structure type of the customized version
print(nodeList.Attributes["id"].Value);
print(nodeList.Attributes["size"].Value);
//or
print(nodeList.Attributes.GetNamedItem("id").Value);
print(nodeList.Attributes.GetNamedItem("size").Value);
//Get the elements in the array directly
XmlNode tempNodeList1 = root.SelectSingleNode("ItemList1");
XmlNodeList xmlNodeList1 = tempNodeList1.SelectNodes("Item");
//Find all the nodes in the List and print the InnerText of the id size node in the node group.
//var type cannot be inferred XmlNode type
foreach (XmlNode item in xmlNodeList1)
{
print(item.Name);
print(item.SelectSingleNode("id").InnerText);
/*
2003> Access the content in the middle through InnerText
17.5>
>*/
print(item.SelectSingleNode("size").InnerText);
}
for (int i = 0; i < xmlNodeList1.Count; i++)
{
print(xmlNodeList1[i].Name);
print(xmlNodeList1[i].SelectSingleNode("id").InnerText);
print(xmlNodeList1[i].SelectSingleNode("size").InnerText);
}
//Get the elements in the array directly. In the form of innerText access, or get Attributes["size"].Value to access the value.
//-------Pay attention to distinguish whether there are child nodes in the element. Select to obtain the node content based on whether there are child nodes.
XmlNode tempNodeList = root.SelectSingleNode("ItemList");
XmlNodeList xmlNodeList = tempNodeList.SelectNodes("Item");
//Find all the nodes in the List and print the InnerText of the id size node in the node group.
//var type cannot be inferred XmlNode type
foreach (XmlNode item in xmlNodeList)
{
print(item.Name);
print(item.Attributes["id"].InnerText);
print(item.Attributes["size"].Value);
}
for (int i = 0; i < xmlNodeList.Count; i++)
{
print(xmlNodeList[i].Name);
print(xmlNodeList[i].Attributes["id"].Value); //
//Single-line embedded access via Attributs["name"].Value
print(xmlNodeList[i].Attributes["size"].Value);
}
//============================Read================
//==================xml storage path
// 1.Resources is readable but not writable and cannot be found after packaging ×
// 2.Application.streamingAssetsPath is readable and writable on the PC side and can be found ×
// 3.Application.dataPath cannot be found after packaging ×
// 4.Application.persistentDataPath is readable and writable and can be found √
string path = Application.streamingAssetsPath + "/xmlSaveFile.xml";
print(Application.persistentDataPath);
//Create fixed version information
XmlDocument saveXmlFile = new XmlDocument();
//File format declaration
XmlDeclaration xmlDeclaration = saveXmlFile.CreateXmlDeclaration("1.0", "utf-8", "");
saveXmlFile.AppendChild(xmlDeclaration);
//Add root node
//Here is an example of storing class information
XmlElement classInfo =saveXmlFile.CreateElement("ClassInfo");
saveXmlFile.AppendChild(classInfo);
//Create child nodes
XmlElement teacher = saveXmlFile.CreateElement("teacher");
classInfo.AppendChild(teacher);
XmlElement teacherName = saveXmlFile.CreateElement("teacherName");
teacherName.InnerText = "TonyChang";
teacher.AppendChild(teacherName);
XmlElement teacherId = saveXmlFile.CreateElement("teacherId");
teacherId.InnerText = "3306";//Set teacherID name
teacher.AppendChild(teacherId);
//Student information module
XmlElement stusElement = saveXmlFile.CreateElement("Students");
XmlElement stuEle;//Student information
for (int i = 0; i 8888
changeNode.InnerText = "8888";
//---Delete (delete through parent node)
XmlNode FatherNode = Xml1.SelectSingleNode("ClassInfo/teacher");
FatherNode.RemoveChild(changeNode);
//---Add new node
XmlNode changedNode=Xml1.CreateElement("teacherId");
changedNode.InnerText = "8888";
FatherNode.AppendChild(changedNode);
//Remember to save if modified
Xml1.Save(path);
}
}
}
}
textXML file
TonyChang
18
175.5>
1998>
12.25
>
2002>
16.5>
>
2003>
17.5>
>
2004>
18.5>
>
The file format is as shown in the figure;
Generate the contents of the new “xmlSaveFile.xml” file
XMLserialization and deserialization
Serialization:
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;
public class Test
{
public int testPub = 10;
private int testPri = 5;
protected int testProtect = 12;
internal int testInter = 15;
public string testStr = "TonyChang";
//Attributes
public int testPro { get; set; }
//array
public int[] arrayInt=new []{2,4,6,8};
//Custom class
public Test2 Test2 = new Test2();
//list
//Change the array attribute name
[XmlArray("IntList")]
[XmlArrayItem("TCInt")]
public List listInt=new List(){1,5,7,8,9};
//Dictionary is not supported
// public Dictionary testDic = new Dictionary() {{1, "Jerry"},{2,"Tom"}};
}
public class Test2
{
//attribute tag
[XmlAttribute("Test2")] public int xmlTest = 5;
[XmlAttribute()] public float test2Float = 6.6f;
[XmlAttribute()] public bool aryUok = true;
}
///
/// XML serialization and deserialization
///
public class XMLDemo : MonoBehaviour
{
private void Start()
{
//File stream to be stored as XML file
Test test = new Test();
string path = Application.persistentDataPath + "/XMLTest01.xml";
print(path);
//flow statement
//using file loading, the file will automatically close after loading.
using(StreamWriter stream = new StreamWriter(path) )
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test));
//Serialize the XML file and write it into the stream
//The stream is set according to the configured write address
xmlSerializer.Serialize(stream,test);
}
}
}
- Only public type variables can be stored
- Dictionary storage is not supported
The corresponding generated XML file is as shown below:
Deserialization:
//Deserialization
//Determine whether there is an XML file to be read
if (File.Exists(path))
{
using (StringReader reader = new StringReader(path))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test));
Test testReaded=xmlSerializer.Deserialize(reader) as Test;
}
}
//tips:
//When there is a default value in the list object, the default value will be added to the list array again during deserialization.
//It can be understood that the default values (initial values) of various variables need to be examined during current deserialization.
//If it is serialized by itself, there will be assignment operations such as new List(){1,2,3}
//Then the values 1, 2, and 3 will be re-added to the list array during deserialization, and the obtained
//There will be two contents of 1, 2, 3 1, 2, 3 in the deserialization result
stDic = new Dictionary() {{1, “Jerry”},{2,”Tom”}};
}
public class Test2
{
//attribute tag
[XmlAttribute(“Test2”)] public int xmlTest = 5;
[XmlAttribute()] public float test2Float = 6.6f;
[XmlAttribute()] public bool aryUok = true;
}
///
///
public class XMLDemo : MonoBehaviour
{
private void Start()
{
//File stream to be stored as XML file
Test test = new Test();
string path = Application.persistentDataPath + “/XMLTest01.xml”;
print(path);
//flow statement
//using file loading, the file will automatically close after loading.
using(StreamWriter stream = new StreamWriter(path) )
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test));
//Serialize the XML file and write it into the stream
//The stream is set according to the configured write address
xmlSerializer.Serialize(stream,test);
}
}
}
- Only public type variables can be stored
- Dictionary storage is not supported
The corresponding generated XML file is as shown below:
Deserialization:
//Deserialization
//Determine whether there is an XML file to be read
if (File.Exists(path))
{
using (StringReader reader = new StringReader(path))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Test));
Test testReaded=xmlSerializer.Deserialize(reader) as Test;
}
}
//tips:
//When there is a default value in the list object, the default value will be added to the list array again during deserialization.
//It can be understood that the default values (initial values) of various variables need to be examined during current deserialization.
//If it is serialized by itself, there will be assignment operations such as new List(){1,2,3}
//Then the values 1, 2, and 3 will be re-added to the list array during deserialization, and the obtained
//There will be two contents of 1, 2, 3 1, 2, 3 in the deserialization result