This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

An overview of the

XML file and Json file are also very important in Unity development process. In fact, the core is to deal with strings. One is an XML string and the other is a Json string, especially if you’re dealing with network requests. This article explains the use of XML files in Unity, hope to help you.

What is the XML

XML stands for EXtensible Markup Language. Is a text file that is used to transfer and store data, much like HTML. XML is designed to transmit data, not display it. XML tags are not predefined. You need to define your own tags. XML is designed to be self-descriptive. Is a W3C recommendation.

Using XML in Unity

In Unity, there are often situations where you have to deal with a large number of strings, where XML is very important. And XML file structure hierarchy is clear, very practical. To use Unity, you first need to reference the namespace using System.xml; Using system. IO; This is the namespace in which operations are performed on files (read files, etc.). The next step is to add, delete, modify and check the XML file.

Create an XML

First look at the creation code:

Public void createXml() {// The path where the XML is saved. string filepath = Application.dataPath + @"/student.xml"; // Check whether the file exists in the current path if (! File.exists (filepath)) {// create an XML document instance XmlDocument xmlDoc = new XmlDocument(); XmlElement root = xmlDoc.createElement ("Students"); XmlElement root = xmlDoc.createElement ("Students"); XmlElement elmNew = xmlDoc.createElement ("StudentInfo"); // Add two attribute ids to the node and NAME elmnew.setAttribute (" ID ", "0"); Elmnew.setattribute ("name", "three "); XmlElement _class = xmlDoc.createElement ("Class"); // Set the value in the node _class.InnerText = "every three years "; XmlElement number = xmlDoc.CreateElement("Number"); number.InnerText = "20210101"; XmlElement mobile = xmlDoc.CreateElement("Mobile"); mobile.InnerText = "13188888888"; Elmnew.appendchild (_class); // add the nodes to XMLDoc layer by layer. Look carefully at the sequence in which the XML file is generated. elmNew.AppendChild(number); elmNew.AppendChild(mobile); root.AppendChild(elmNew); xmlDoc.AppendChild(root); // Save the XML file to the local xmldoc.save (filepath); Debug.Log("createXml OK!" ); }}Copy the code

Running the above code will create a file named student. XML with the following XML content:

Now let’s look at the method used in the above code: XmlDocument:

  • CreateElement: Creates a node
  • AppendChild: adds a node to make the added node a child node, paying attention to the order in which it is written
  • Save: Saves the XML file

XmlElement:

  • SetAttribute: sets node attributes
  • InnerText: sets the content of the node
  • AppendChild: adds the node, making the added node a child node)

Just one layer of setup is needed to create a hierarchical XML file.

Add data to an XML file

The principle of the XML query is similar to the above, but there is an additional step to load the XML file and obtain the XML file node method. The specific code is as follows:

public void AddXml() { string filepath = Application.dataPath + @"/student.xml"; if (File.Exists(filepath)) { XmlDocument xmlDoc = new XmlDocument(); // Read the XML file xmldoc.load (filepath); XmlNode root = xmldoc.selectSinglenode ("Students"); XmlElement elmNew = xmlDoc.CreateElement("StudentInfo"); elmNew.SetAttribute("id", "1"); Elmnew.setattribute ("name", "li4 "); XmlElement _class = xmlDoc.CreateElement("Class"); _class.InnerText = "class 1 every 3 years "; XmlElement number = xmlDoc.CreateElement("Number"); number.InnerText = "20210102"; XmlElement mobile = xmlDoc.CreateElement("Mobile"); mobile.InnerText = "15866666666"; elmNew.AppendChild(_class); elmNew.AppendChild(number); elmNew.AppendChild(mobile); root.AppendChild(elmNew); xmlDoc.AppendChild(root); xmlDoc.Save(filepath); Debug.Log("AddXml OK!" ); }}Copy the code

Finally, we have implemented the operation of adding a file to the XML, and the result of the run is

We will also find that we use an XmlElement when we create it, and an XmlNode when we add it. What is the difference between them?

  • XmlElement inherits from XmlNode.
  • There are many types of Xml nodes: attribute nodes, comment nodes, text nodes, element nodes, and so on. XmlNode is a general term for these nodes, and XmlElement is an element node.

Example Modify the content of an XML file

The general idea of modifying an XML file is to take the node you want to modify, and then use InnerText to change the parameters you want to modify. Next, let’s change the name of Li Si in the XML created above to li Si wu mobile number 222222222. Let’s see how it works. Firstly, all child nodes under the root node Students should be obtained, and then traversal all child nodes to find the node whose attribute name is Li 4, then traversal the node whose attribute name is Li 4, and find the Mobile node, and then set its Mobile phone number to 222222222, and finally save the file. The specific implementation script is:

public void UpdateXml() { string filepath = Application.dataPath + @"/student.xml"; if (File.Exists(filepath)) { XmlDocument xmlDoc = new XmlDocument(); Xmldoc.load (filepath); XmlNodeList nodeList = xmlDoc.SelectSingleNode("Students").childNodes; Foreach (XmlElement xe in nodeList) {if (xe.getAttribute ("name") == "name") {// update the attribute of the node Xe.setattribute ("name", "li4 "); Foreach (XmlElement x1 in xe.childnodes) {if (x1.name == "Mobile") {// x1.InnerText = "222222222222"; } } break; } } xmlDoc.Save(filepath); Debug.Log("UpdateXml OK!" ); }}Copy the code

After running, the effect is:

There is something useful in this code that the first two operations did not use:

  • ChildNodes: gets all ChildNodes, but does not include the ChildNodes in the ChildNodes
  • GetAttribute: Gets the node attribute

Delete the content in the XML

The only difference is that SetAttribute or InnerText is used for a change, while RemoveAttribute or RemoveAll is used for a delete. To find the attribute or node to be deleted, use RemoveAttribute or RemoveAll to operate the data. Next, let’s delete The ID attribute and the Mobile attribute. The specific code is as follows:

public void deleteXml() { string filepath = Application.dataPath + @"/student.xml"; if (File.Exists(filepath)) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filepath); XmlNodeList nodeList = xmlDoc.SelectSingleNode("Students").ChildNodes; Foreach (XmlElement xe in nodeList) {if (xe.getAttribute ("name") == "li 4 5 ") {// remove the node attribute xe.removeAttribute ("id"); } foreach (XmlElement x1 in xe.childnodes) {if (x1.name == "Mobile") {// remove the x1.removeall (); } } } xmlDoc.Save(filepath); Debug.Log("deleteXml OK!" ); }}Copy the code

The results are as follows

conclusion

This is the most primitive way to manipulate XML in Unity. There are more advanced ways to manipulate XML files through encapsulation or serialization and deserialization, which will be introduced later. In this article, on the whole, the code is easy, create and add the XML file code has always been so few words, and finally with respect to OK, pay attention to the sequence and hierarchy and modify, and delete XML file, is the first traverse all the nodes, then found to be modified to modify, or delete nodes, namely a few main parameters.

Write in the last

All the shared content are the author in the daily development process used a variety of small function points, share out also in a disguised review, if there is a bad place to write also please give advice. The source code of the Demo will be sorted out and shared later. Welcome to learn from each other and make progress.