I have the following XML file:
<world>
<tile x="-2" y="0" z="4">
<item id="3" />
</tile>
<tile x="-3" y="0" z="4">
<item id="3" />
</tile>
</world>
world encompasses and array of tiles and each tile encompasses an array of items (not shown in this file).
I’m using the following function to deserialize the file:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;
[XmlRoot("world")]
public class WorldContainer
{
[XmlArray("tile")]
public Tile[] tiles;
//load XML file
public static WorldContainer Load(string path)
{
var serializer = new XmlSerializer(typeof(WorldContainer));
using(var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as WorldContainer;
}
}
Here are the classes involved:
Tile class
using UnityEngine;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
//Holds the stack and properties of each point in the game world
public class Tile {
[XmlArray("item")]
public List<Item> stack;
[XmlAttribute("x")]
public int x;
[XmlAttribute("y")]
public int y;
[XmlAttribute("z")]
public int z;
public Tile()
{
//stack = new List<Item> ();
}
public Tile(int X, int Y, int Z)
{
x = X;
y = Y;
z = Z;
stack = new List<Item> ();
}
// Update is called once per frame
void Update () {
}
}
Item class
using UnityEngine;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
public class Item {
[XmlAttribute("id")]
public int id;
[XmlIgnore]
public GameObject item;
[XmlIgnore]
public int stackPos;
[XmlIgnore]
public int y;
public Item()
{
}
public Item(int Id, GameObject x, int stackpos, int yvalue)
{
id = Id;
item = x;
stackPos = stackpos;
int y = yvalue;
//typo?
}
public Item (Item copy)
{
id = copy.id;
item = copy.item;
stackPos = copy.stackPos;
y = copy.y;
}
public Item(GameObject x)
{
item = x;
worldObject properties = x.GetComponent<worldObject>();
stackPos = properties.stackPosType;
y = GUI.SelectedLevel;
}
}
Once I try to load and deserialize the file I do this:
var grid = WorldContainer.Load (Path.Combine (Application.dataPath, "Resources/XMLFiles/" + fileName));
//iterate through each tile and item read from the XML file
int i = 0, j = 0;
foreach(Tile tile in grid.tiles)
{
Debug.Log ("Tile "+i+": coordinates ("+tile.x+", "+tile.y+", "+tile.z+")");
foreach(Item item in tile.stack)
{
Debug.Log ("Item "+j+" id= "+item.id);
j++;
}
i++;
}
Debug.Log ("Finished reading...");
}
It comes back with nothing, it only returns one tile and the coordinates are 0,0,0 which is not true if you look at the XML file.
I haven’t had much luck dealing with XML, I’ve found articles and examples but they are confusing and I cannot figure out what is wrong.
Any input is appreciated, thanks in advance