简体   繁体   中英

C# - parse xml nodes

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.

If you need read all points, you can use

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

SelectNodes return a list of nodes.

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")
                })
            });
        }
    }
}
​

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM