Question

I'm not sure how to go about doing a deep copy of a XML file that is stored in a list. I had read up on some of the post here, Some uses Serialize & some uses Icloneable. which method is the best?

Currently I had only read the XML files and store it in a list.

TextAsset XMLFile;
public GameObject spawnAlert;

List<AlertInfo> m_AlertInfo = new List<AlertInfo>();

public class AlertInfo
{
    public string strId     { get; set; }
    public string strName   { get; set; }
    public Vector3 vectSpawnPos = new Vector3();
}

void Start()
{
    TextAsset textXML = (TextAsset)Resources.Load("Alert", typeof(TextAsset));
    XmlDocument xml = new XmlDocument();
    xml.LoadXml(textXML.text);


    XmlNode root = xml.FirstChild;

    for( int x = 0; x < root.ChildNodes.Count; x++)
    {
        AlertInfo alertI = new AlertInfo();

        alertI.strId = root.ChildNodes[x].Attributes[0].Value;
        alertI.strName = root.ChildNodes[x].Attributes[1].Value;

        alertI.vectSpawnPos.x = float.Parse( root.ChildNodes[x].Attributes[2].Value);
        alertI.vectSpawnPos.y = float.Parse( root.ChildNodes[x].Attributes[3].Value);
        alertI.vectSpawnPos.z = float.Parse( root.ChildNodes[x].Attributes[4].Value);

        m_AlertInfo.Add( alertI );
    }

<ListOfAlerts>
    <AlertInfo id = "1"     Name = "Unsecured Aircraft"                                     pos_X = "0" pos_Y = "0" pos_Z = "0" />
    <AlertInfo id = "2"     Name = "Suspecious Baggage Found at Lobby"                          pos_X = "0" pos_Y = "0" pos_Z = "0" />
    <AlertInfo id = "3"     Name = "Disruptive person at Departure Hall"                                pos_X = "0" pos_Y = "0" pos_Z = "0" />
    <AlertInfo id = "4"     Name = "Suspicious person loitering around at Arrival Hall"             pos_X = "0"pos_Y = "0"  pos_Z = "0" />
</ListOfAlerts>
Was it helpful?

Solution

How about using LINQ to XML ?

XDocument xDoc = XDocument.Parse("textXML.text");

var myList = xDoc.Descendants("AlertInfo").Select(x => new AlertInfo()
        {
            strId = (string) x.Attribute("id"),
            strName = (string) x.Attribute("Name"),
            vectSpawnPos = new Vector3
            {
                x = (float) x.Attribute("pos_X"),
                y = (float) x.Attribute("pos_Y"),
                z = (float) x.Attribute("pos_Z")
            }
        }).ToList();

To use this code you need to make a little change.Make your vectSpawnPos auto-implemented property like:

public Vector3 vectSpawnPos { get; set; }

And your Vector3 class should look like:

public class Vector3
{
    public float x { get; set; }

    public float y { get; set; }

    public float z { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top