- Home /
Question by
rishabhvinod · Sep 04, 2013 at 08:55 AM ·
how can i parse xml through API in unity please can anyone explain with some example.
I am trying to parse an XML through API . XML is loading but unable to read nodes of the xml, please can anyone help me with some suitable example from which i can read nodes of my XML and display in GUI.
Thanks in advance
Comment
Best Answer
Answer by rishabhvinod · Sep 04, 2013 at 12:27 PM
Hi Guys i got the solution and i am shring with you all for reference....
using System.Collections; using UnityEngine; using System.Xml.Serialization; using System.Xml; using System.Collections.Generic; using System.IO; using System;
public class newLoad : MonoBehaviour {
private string _url = "your API or url of xml";
private string _xml;
Vector2 scrollPosition = Vector2.zero;
XmlDocument xmlDoc = new XmlDocument();
List<Dictionary<string,string>> levels = new List<Dictionary<string,string>>();
Dictionary<string,string> obj;
ArrayList listItems = new ArrayList();
IEnumerator Start() {
// Start a download of the given URL
WWW www = new WWW(_url);
// Wait for download to complete
yield return www;
// get text
_xml = www.text;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(www.text);
Debug.Log(_xml);
print(xmlDoc);
// having XML here. Do with it whatever you want...
XmlNodeList levelsList = xmlDoc.GetElementsByTagName("MainCategories");
foreach (XmlNode levelInfo in levelsList)
{
//Debug.Log("foreach inner");
string str = levelInfo.InnerXml;
XmlNodeList levelcontent = levelInfo.ChildNodes;
obj = new Dictionary<string,string>();
// Debug.Log("MainCategories = " + str);
foreach (XmlNode levelsItens in levelcontent)
{
//Debug.Log("~~~~~~First Node~~~~~");
Dictionary<string,string> obj1 = new Dictionary<string,string>();
if(levelsItens.Name == "MainCategory")
{
//Debug.Log("~~~~~~Second Node~~~~~");
string str1 = levelsItens.Name;
obj1.Add("MainCategory",levelsItens.InnerText);
// Debug.Log("MainCategory = " + str1);
foreach (XmlNode levelsItens1 in levelsItens)
{
//Debug.Log("~~~~~~Third Node~~~~~");
Dictionary<string,string> obj2 = new Dictionary<string,string>();
if(levelsItens1.Name == "MainCategoryID")
{
string str2 = levelsItens1.InnerXml;
obj2.Add("MainCategoryID",levelsItens1.InnerText);
Debug.Log("MainCategoryID = " + str2);
}
if(levelsItens1.Name == "MainCategoryTitle")
{
string str3 = levelsItens1.InnerXml;
obj2.Add("MainCategoryTitle",levelsItens1.InnerText);
Debug.Log("MainCategoryTitle = " + str3);
if(str3 != "NULL"){
listItems.Add(str3);
}
}
}
}
}
}
}
void OnGUI () {
GUILayout.BeginArea(new Rect(0f, 0f, 300f, 200f), GUI.skin.window);
scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, true);
GUILayout.BeginVertical(GUI.skin.box);
foreach (string item in listItems)
{
GUILayout.Label(item, GUI.skin.box, GUILayout.ExpandWidth(true));
}
GUILayout.EndVertical();
GUILayout.EndScrollView();
GUILayout.EndArea();
}