1

I am loading my data from XML using C# this way:

XmlDocument xmlDoc = new XmlDocument();
TextAsset xmlFile = Resources.Load("levels/" + levelID) as TextAsset;
xmlDoc.LoadXml(xmlFile.text);

XmlNodeList levelsList = xmlDoc.GetElementsByTagName("level");

foreach (XmlNode levelInfo in levelsList)
{
    XmlNodeList childNodes = levelInfo.ChildNodes;

    foreach (XmlNode value in childNodes)
    {
        switch (value.Name)
        {
            case "info":
                //levelWidth = getInt(value, 0);
                //levelHeight = getInt(value, 1);
                break;
        }
    }
}

And heres XML I am loading:

<?xml version="1.0" encoding="utf-8" ?>
<level>
  <info w="1000" h="500"/>
</level>

It works just fine, I am now trying to find best way to load child nodes, inside my level node with multiple points nodes inside

<?xml version="1.0" encoding="utf-8" ?>
<level>
    <info w="1000" h="500"/>
    <ground>
      <point val1="val1" val2="val2"/>
    </ground>
</level>

I will be grateful for some guidance how to move in the right direction, thank you.

3
  • 5
    Firstly, I'd strongly recommend that you move to using LINQ to XML if you possibly can. It's considerably better in any number of ways. Next, rather than reading all the nodes and then switching on what they are, I would look for specific elements and handle them appropriately. Commented Nov 30, 2015 at 20:13
  • I think that this question is for CodeReview service. If everything works fine and you want to make improved then you need to try CodeReview Commented Nov 30, 2015 at 20:14
  • You need read all poins? Commented Nov 30, 2015 at 20:23

3 Answers 3

1

Using XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
             "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
            "<level>" +
                "<info w=\"1000\" h=\"500\"/>" +
            "</level>";

            XDocument doc = XDocument.Parse(xml);

            XElement level = (XElement)doc.FirstNode;

            level.Add("ground", new object[] {
                new XElement("point", new XAttribute[] {
                    new XAttribute("val1", "val1"),
                    new XAttribute("val2", "val2")
                })
            });
        }
    }
}
​
Sign up to request clarification or add additional context in comments.

Comments

1

If you need read all points, you can use

var nodeList = Xmldocument.SelectNodes("level/info/ground/point");

SelectNodes return a list of nodes.

Comments

0

I would go for a slidely different way and use a data object. Then you don't have to analyse xml, you just code your data class:

[Serializable()]
public class CLevel
{
    public string Info { get; set; }
}

[Serializable()]
public class CDatafile
{
    public List<CLevel> LevelList { get; set; }

    public CDatafile()
    {
        LevelList = new List<CLevel>();
    }
}

public class DataManager
{
    private string FileName = "Data.xml";
    public CDatafile Datafile { get; set; }

    public DataManager()
    {
        Datafile = new CDatafile();
    }

    // Load file
    public void LoadFile()
    {
        if (System.IO.File.Exists(FileName))
        {
            System.IO.StreamReader srReader = System.IO.File.OpenText(FileName);
            Type tType = Datafile.GetType();
            System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
            object oData = xsSerializer.Deserialize(srReader);
            Datafile = (CDatafile)oData;
            srReader.Close();
        }
    }

    // Save file
    public void SaveFile()
    {
        System.IO.StreamWriter swWriter = System.IO.File.CreateText(FileName);
        Type tType = Datafile.GetType();
        if (tType.IsSerializable)
        {
            System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
            xsSerializer.Serialize(swWriter, Datafile);
            swWriter.Close();
        }
    }

Then you can use it to create, save and load the file like this:

DataManager dataMng = new DataManager();

// Create some data
CLevel level = new CLevel();
level.Info = "Testlevel";
dataMng.Datafile.LevelList.Add(level);

// Save to file
dataMng.SaveFile();

// Load from file
dataMng.LoadFile();

So you can do everything in code checked by the compiler. Makes life a lot easier, or what do you think?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.