Parse Xml in Unity3D

Parse Xml in Unity3D

Have a .xml file that needs parsing in unity? Let us learn what is an xml file and how you can parse xml in unity3d.

What is an Xml?

XML stands for eXtensible Markup Language. It is a software- and hardware-independent tool for storing and transporting data. It can be used to save your data in Unity.

XML documents must contain one root element that is the parent of all other elements.

<root>
  <child>
    <subchild>.....</subchild>
  </child>
</root>

This line is called the XML prolog:

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

The XML prolog is optional. If it exists, it must come first in the document.

In XML, it is illegal to omit the closing tag. All elements must have a closing tag. <child> has closing tag </child>. Also, XML tags are case sensitive. 

Here is an example of an xml:

<?xml version="1.0"?>
<PlayerData>
   <lives>3</lives>
   <currentLevel>1</currentLevel>
</PlayerData>

This xml corresponds to a class PlayerData with two variables: playerLives and currentLevel.

public class PlayerData
{
    public int lives;
    public int currentLevel;
}

Parse XML in Unity3D

When File is present at Application.persistentDataPath

We use XmlSerializer for parsing the data.

   string filePath = Path.Combine(Application.persistentDataPath, "filename.xml"); 
    PlayerData LoadData()
    {
        if (File.Exists(filePath))
        {
            string fileText = File.ReadAllText(filePath);
            XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
            using (StringReader reader = new StringReader(fileText))
            {
                return (PlayerData)(serializer.Deserialize(reader)) as PlayerData;
            }
        }
        return null;
           
    }

Here, first we check if the file exists. Then we deserialize the StringReader to return an object of the type PlayerData in this case.

When File is present in Resources Folder

   string fileName = "fileName";
    XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
    string data = Resources.Load<TextAsset>(fileName).text;
    using (StringReader reader = new StringReader(data))
    {
        playerData = (serializer.Deserialize(reader)) as PlayerData;
    }

Saving an Xml File

Now, if we want to save the player data to an xml file, we can do this like:

   string filePath = Path.Combine(Application.persistentDataPath, "filename.xml"); 
    void SaveData(PlayerData data)
    {
        var serializer = new XmlSerializer(typeof(PlayerData));

        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            serializer.Serialize(stream, data);
        }
    }

We Serialize the FileStream to save the PlayerData object (here data) in the xml file at path given by filePath.

It is not recommended to use Resources folder when saving data in an xml because there isnt an actual “Resources” folder available in build.

Happy Parsing!

Share This Post

Post Comment