Hello World!


Hello World!

Hello everyone, I'm creating this blog with the purpose of sharing my and your ideas with all hungry for game development.

Follow Tweeter

empty space


Sunday, February 27, 2011

XML - Loading data from a xml file.

Hello everyone, in this post i pretend to show how to use a external file(xml) with texts or values in your game. I made the main script in c#. The intention is to show a conversation when you comes close to a object. Let's Work!




This is the code of the xml file which i call gamexmldata.xml:


  
    Level 1 (xml)
    Try comes close to all four objects. (xml)
     Hi, I'm a cube! (xml) 
     Hi, I'm a Cylinder! (xml) 
     Hi, I'm a Capsule! (xml) 
     Hi, I'm a Sphere! (xml)
    Very Good! (xml)
  
  
    Level 2 (xml)
    Try comes close to all four objects, again. (xml)
     Hi, I'm a cube in the level 2! (xml)
     Hi, I'm a Cylinder in the level 2! (xml)
     Hi, I'm a Capsule in the level 2! (xml)
     Hi, I'm a Sphere in the level 2! (xml)
    Congratulations! (xml)
  


Ok this is our data, now we need to assign these values to variables or arrays.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
 
 
public class LoadXmlData : MonoBehaviour // the Class
{
 public TextAsset GameAsset;
 
 static string Cube_Character = "";
 static string Cylinder_Character = "";
 static string Capsule_Character = "";
 static string Sphere_Character = "";
 
 List<Dictionary<string,string>> levels = new List<Dictionary<string,string>>();
 Dictionary<string,string> obj;
 
 void Start()
 { //Timeline of the Level creator
  GetLevel();
 }
 
 public void GetLevel()
 {
  XmlDocument xmlDoc = new XmlDocument(); // xmlDoc is the new xml document.
  xmlDoc.LoadXml(GameAsset.text); // load the file.
  XmlNodeList levelsList = xmlDoc.GetElementsByTagName("level"); // array of the level nodes.
 
  foreach (XmlNode levelInfo in levelsList)
  {
   XmlNodeList levelcontent = levelInfo.ChildNodes;
   obj = new Dictionary<string,string>(); // Create a object(Dictionary) to colect the both nodes inside the level node and then put into levels[] array.
   
   foreach (XmlNode levelsItens in levelcontent) // levels itens nodes.
   {
    if(levelsItens.Name == "name")
    {
     obj.Add("name",levelsItens.InnerText); // put this in the dictionary.
    }
   
    if(levelsItens.Name == "tutorial")
    {
     obj.Add("tutorial",levelsItens.InnerText); // put this in the dictionary.
    }
   
    if(levelsItens.Name == "object")
    {
     switch(levelsItens.Attributes["name"].Value)
     {
      case "Cube": obj.Add("Cube",levelsItens.InnerText);break; // put this in the dictionary.
      case "Cylinder":obj.Add("Cylinder",levelsItens.InnerText); break; // put this in the dictionary.
      case "Capsule":obj.Add("Capsule",levelsItens.InnerText); break; // put this in the dictionary.
      case "Sphere": obj.Add("Sphere",levelsItens.InnerText);break; // put this in the dictionary.
     }
    }
   
    if(levelsItens.Name == "finaltext")
    {
     obj.Add("finaltext",levelsItens.InnerText); // put this in the dictionary.
    }
   }
   levels.Add(obj); // add whole obj dictionary in the levels[].
  }
 }
}


with this method we're created a Array with the all level node info inside and to get this values you need just do this:

string lvlName = "";
  levels[actualLevel-1].TryGetValue("name",out lvlName);
 
  string tutorial = "";
  levels[actualLevel-1].TryGetValue("tutorial",out tutorial);
 
  levels[actualLevel-1].TryGetValue("Cube",out Cube_Character);
  levels[actualLevel-1].TryGetValue("Cylinder",out Cylinder_Character);
  levels[actualLevel-1].TryGetValue("Capsule",out Capsule_Character);
  levels[actualLevel-1].TryGetValue("Sphere",out Sphere_Character);
 
  string finaltext = "";
  levels[actualLevel-1].TryGetValue("finaltext",out finaltext);



So that's it. Here you can download the fully functioning project. There are many possibilities, this is only one way, I hope you enjoyed it, give your comments!


33 comments:

  1. thank you. I'll try.

    ReplyDelete
  2. Can you not do this in Javascript? I just get XmlDocument does not denote a valid type. (not found)

    ReplyDelete
    Replies
    1. Nevermind.... import System.Xml for javascript. (im new sorry)

      Delete
  3. Hi, I'm trying to understand the script example but I'm confused by something: the name "gamexmldata.xml", which is the xml file itself is never mentioned in the XML reader proc. So how can it know that you mean to load that file?

    ReplyDelete
    Replies
    1. i'm using public TextAsset GameAsset; you need to put the file there in the inspector.

      Delete
  4. Thanks for this article...Really helpful

    ReplyDelete
  5. Wow, thx. This helps a lot.

    ReplyDelete
  6. HELP ME !
    I download xml from www than save(replace) in ressources folder , but when i want same operation on large xml with <![DATA than i get

    XmlException: Text node cannot appear in this state. Line 1, position 1.
    Mono.Xml2.XmlTextReader.ReadText (Boolean notWhitespace)

    ReplyDelete
  7. Thanks this simplified walkthrough is exactly what I needed

    ReplyDelete
  8. Thanks! Helped me alot.

    Created a www get webserver xml file. Inside that xml i have the latest version number and news items.
    Used your code to process that xml data for version check and to show news items ingame :D..

    Works great now.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Okay, it has been a long time. I am using javascript and I did - import System.Xml in my script. I even tried having the dll in my assests folder. But I still get the "The name 'XmlDocument', 'XmlNode' does not denote a valid type ('not found'). " I am using Unity 5. Any idea?

    ReplyDelete
  12. Hi, im using Unity 5.2 and "using System.Xml;" is not found, there is any other way to call the XML libraries in order to use it in the program?? im programming in C#

    ReplyDelete
  13. The Extensible Markup Language can best be defined as a subset of the Standard Generalized Markup Language. It is called 'extensible' because it allows users to add their own elements in it. You Can see more in : xml file

    ReplyDelete
  14. what the problem if it code can't show text? but no error in unity

    ReplyDelete
  15. i want run run c# script via online you have any solution ? please help mw

    ReplyDelete
  16. Best Xml Tutorial on the Internet

    ReplyDelete
    Replies
    1. tank you very much! unfortunately I can't recover my Hotmail account that I create this blog, because that I can't update this blog.

      Delete
    2. tank you very much! unfortunately I can't recover my Hotmail account that I create this blog, because that I can't update this blog.

      Delete
  17. Check this one, many methods to read xml file

    ling

    ReplyDelete
  18. In this method

    string lvlName = "";
    levels[actualLevel-1].TryGetValue("name",out lvlName);

    string tutorial = "";
    levels[actualLevel-1].TryGetValue("tutorial",out tutorial);

    levels[actualLevel-1].TryGetValue("Cube",out Cube_Character);
    levels[actualLevel-1].TryGetValue("Cylinder",out Cylinder_Character);
    levels[actualLevel-1].TryGetValue("Capsule",out Capsule_Character);
    levels[actualLevel-1].TryGetValue("Sphere",out Sphere_Character);

    string finaltext = "";
    levels[actualLevel-1].TryGetValue("finaltext",out finaltext);

    How would you select level 2 node and tutorial for example. Thanks, Its working but only reading the first level xml. Thank You. Great Example

    ReplyDelete
    Replies
    1. I think, the level node is given by the array position, using the actualLevel as index you can switch each level easily.

      Delete
  19. An excellent tutorial. I am also having the same trouble as the commenter above (May 22 2017). I can use the method to output part of the first xml entry but none of the others.

    ReplyDelete
  20. Very awesome post!
    Spent a day and a night trying to figure this out, read just about every post on the forums and had something going with different classes, arrays and all kinds of stuff that was way too abstract for me. Your solution was exactly what I was looking for and gave me an easy to understand control of the data.

    Thanks!

    thegamerealm.com

    ReplyDelete
  21. Good post for loading data from xml file in C# Asp.Net.

    ReplyDelete