Reading XML file using xmlReader

hey all, below is a working script for using an xml file and reading each of it’s nodes :slight_smile:

am not sure if something like this is already posted

using UnityEngine;
using System.Collections;
using System.Xml;
using System.IO;
using System.Text;

public class xmlTest : MonoBehaviour {
	
  //  assuming i have this xml 
	string xmlString = "<?xml version=\"1.0\" ?> " +
		"<school>" +
		"<student>" +
		"<id>1</id>" +
                "<Fname>john</Fname>" +
		"<Lname>last name</Lname>" +
		"</student>" +
		"<student>" +
		"<id>2</id>" +
		 "<Fname>lily</Fname>" +
		"<Lname>something</Lname>" +
		"</student>" +
		"</school>";
 
   
	// Use this for initialization
	void Start () 
	{ 
               ReadXmlData(xmlString );
	}
	
	
	void ReadXmlData(string XmlDataString)
	{ 
		using (XmlReader reader = XmlReader.Create(new StringReader(XmlDataString)))
		{ 
			reader.MoveToContent();
 
			if (reader.ReadToDescendant("student"))
			{
				do
				{ 
					reader.ReadToDescendant("id"); 
					reader.ReadStartElement("id");  
					print("id : " + reader.Value);	
				 
					reader.ReadToFollowing("Fname"); 
					reader.ReadStartElement("Fname");  
					print("first name: " + reader.Value);					
 
					reader.ReadToFollowing("Lname"); 
					reader.ReadStartElement("Lname");  
					print("last name: " + reader.Value); 
				} 
				while (reader.ReadToFollowing("student"));
			} 
		} 	
	}
	
 
}

I dont know why you are using this method, but there is anothers, just like that:

with that you can serialize your datatypes easily

Write

     XmlSerializer serializer = new XmlSerializer(typeof(Machine[]));
     TextWriter    textWriter = new StreamWriter(Application.absoluteURL+_fileName);
     serializer.Serialize(textWriter, machine );
     textWriter.Close();

Read

     XmlSerializer deserializer = new XmlSerializer(typeof(Machine[]));
     TextReader      textReader = new StreamReader(Application.absoluteURL + _fileName);
     machine = (Machine[])deserializer.Deserialize(textReader);
     textReader.Close();

indeed this is much cleaner

thanks a lot ! it will make my work much easier