how to use data from a XML file

Hi

I have been following this tutorial and I finish it but I dont know how to use the information of the XML file, what I want to do is create a simple dialog system where I can load the name of the speaker and the text so I changed the tutorial from monsters to dialog, here is my code:

this is the XML file:

<?xml version="1.0" encoding="utf-8" ?> 
<DialogCollection>
    <Dialogs>
        <Dialog name="Carlos">
            <text>"Hello sir!"</text>
			<text>"Good day today!"</text>
        </Dialog>
        <Dialog name="Antonio">
            <text>"Hello sir!"</text>
			<text>"Are you gonna buy something today?"</text>
        </Dialog>
    </Dialogs>
</DialogCollection>

The dialog Class

using System.Xml;

using System.Xml.Serialization;

 

public class Dialog{
    [XmlAttribute("name")]
    public string name;
	public string text;
    

}

Dialog container

using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

[XmlRoot("DialogCollection")]
public class DialogContainer
	{
    [XmlArray("Dialogs"),XmlArrayItem("Dialog")]
    public List<Dialog> Dialogs = new List<Dialog>();
	public static DialogContainer Load(string path){
        var serializer = new XmlSerializer(typeof(DialogContainer));
		
        using(var stream = new FileStream(path, FileMode.Open)){
            return serializer.Deserialize(stream) as DialogContainer;
        }
    }
}

And the script where Im supposed to load the dialog to use them

using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using UnityEngine;

public class DialogLoader : MonoBehaviour {
	
void Start(){
		var DialogCollection = DialogContainer.Load(Path.Combine(Application.dataPath, "Dialogos.xml"));
	}
	
}

how can I load, for example the “Carlos” dialog text to show it in screen?

Easiest way would be to just loop through the entries until you found the one you are looking for.

Dialog GetDialog(DialogContainer container, string searchedName)
{
    foreach(var dialog in container.Dialogs)
    {
        if(dialog.name == searchedName)
            return dialog;
    }
    return null;
}

//Usage:
var dialog = GetDialog(DialogCollection, "Carlos");
//now you can use your favorite gui framework and just use "dialog.text" to acess the text you have in the xml

And just a short warning, I am not sure what the xml serializer does by default if you have two nodes and specify no additional hints. Depending on your needs and the behaviour of the serializer might have to change that.
Additionally you won’t need " inside your nodes. If you specify them they will also appear in the string you are trying to display.

Thanks a lot! and thanks for the tutorial too! yeah I was thinking that too, I will use and ID or something to identify the text strings.

It will fail. text should be a string[ ] instead of string if you want the structure to remain the same.