Coverting a XML array to a string array in C#

I’m kinda new to Unity. So I got a language choice in my game using strings stored in a XML. I try to get the xml didYouKnows (Will add many more in that array) array into a string array for a Text object to get one Random when my pause screen popup.

This is my xml

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

<language>
  <Name>French</Name>
  <chooseChar>Choisis ton personnage</chooseChar>
  <didYouKnows>
    <didYouKnow>La superficie de la mine à ciel ouvert Mont-Wright est équivalente à 2 222 terraines de soccer.</didYouKnow>
    <didYouKnow>Un humain, de sa naissance à sa mort, consomme environ 1 450 tonnes de minéraux, de métaux et d'essence.</didYouKnow>
  </didYouKnows>
</language>

<language>
  <Name>English</Name>
  <chooseChar>Choose your character</chooseChar>
  <didYouKnows>
    <didYouKnow>The surface area of the Mont-Wright surface mine is equivalent to 2,222 soccer fields.</didYouKnow>
    <didYouKnow>A human, from birth to death, consumes approximately 1,450 tonnes of minerals, metals and gasoline.</didYouKnow>
  </didYouKnows>
</language>

</languages>

And this is my C# script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Xml;
using System.Text;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class XmlReader : MonoBehaviour
{
    public static XmlReader Instance;


    public TextAsset dictionary;

    public string languageName;
    public static int currentLanguage;

    string chooseChar, menu, startgame, scoreBoard;
    string [] didYouKnows;
    public Text textChooseChar, textMenu, textStartGame, textScoreBoard;

    public Text textDidYouKnow;

    List<Dictionary<string, string>> languages = new List<Dictionary<string, string>>();
    Dictionary<string, string> obj;


    void Awake()
    {
        Reader();
        if (Instance == null)
        {
            DontDestroyOnLoad(gameObject);
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }
    }

    public void FrenchLanguage()
    {
        GameManager.languageSelected = "Fr";
        currentLanguage = 0;
        SelectedLanguage();
        UIFade.instance.FadeToBlack();
        LoadScene.instance.shouldLoadAfterFade = true;
    }

    public void EnglishLanguage()
    {
        GameManager.languageSelected = "En";
        currentLanguage = 1;
        SelectedLanguage();
        UIFade.instance.FadeToBlack();
        LoadScene.instance.shouldLoadAfterFade = true;
    }
    public void SelectedLanguage()
    {
        languages[currentLanguage].TryGetValue("Name", out languageName);
        languages[currentLanguage].TryGetValue("chooseChar", out chooseChar);
        languages[currentLanguage].TryGetValue("didYouKnows", out didYouKnows);
        textChooseChar.text = chooseChar;
        Debug.Log(languageName);
    }

    void Reader()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(dictionary.text);
        XmlNodeList languagesList = xmlDoc.GetElementsByTagName("language");

        foreach (XmlNode languageValue in languagesList)
        {
            XmlNodeList languageContent = languageValue.ChildNodes;
            obj = new Dictionary<string, string>();

            foreach (XmlNode value in languageContent)
            {
                if(value.Name == "Name")
                    obj.Add(value.Name, value.InnerText);
               
                if (value.Name == "chooseChar")
                    obj.Add(value.Name, value.InnerText);
               
            }

            languages.Add(obj);
        }
    }
}

Before you get too deep into this: How married are you to using XML specifically for this? I ask because JSON is far more commonly used in this industry; the files are smaller, they’re faster to read, easier to write and modify, and there are more plugins (Unity’s JsonUtility, LitJson, and Newtonsoft’s Json.NET) that are able to import JSON into a native class structure, which would be preferable to a dictionary. (Also, if I recall correctly, I think including the XML namespace itself in C# adds a truly absurd amount to your build size, like multiple megabytes)

Where you’ve got all this dictionary-crawling in your XML code, if you rewrote your XML to JSON and used Json.NET, you could import it all in one line once you define the data structure. e.g.:

[System.Serializable]
public class LanguageChoice {
public Language[] languages;
}
[System.Serializable]
public class Language {
public string Name;
public string chooseChar;
public string[] didYouKnows;
}

// to load it
JsonSerializer.Deserialize<LanguageChoice>(someJsonText);

That one line of code at the end there replaces all of your entire Reader() function.

Plus, more people will be able to answer questions about it, because it’s more commonly used around these parts. I for example am not familiar enough with the XML classes to know the correct way to load a string array like that.

1 Like

I don’t mind to change to Json. Quite new to both, but I still need to know how I link my strings to the json

What do you mean by this? Do you mean you don’t know how to write the json file?