Giora Guttsait
Giora Guttsait

Reputation: 1300

What would be more appropriate for my need (XML\Json) and how do I use it?

I'm making a game, in C# (MonoGame if it makes a difference), and the game has both a server and a client.
I want the client to hold some kind of textual representation of the items, so that when I load the client it will read the file and parse it into game objects so that I can easily handle items.

I thought about using XML or JSON, I know the basics of both, but I really don't know
How to use them in code.

What do you think would be more appropriate? I think XML is more appropriate but I might be wrong, this is why I'm asking...

The file would have this kind of structure

<items>
  <item>
    <id></id>
    <name></name>
    <cost></cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
  <item>
    <id></id>
    <name></name>
    <cost></cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
</items>

How, given this example structure, do I get the data from the file?

Upvotes: 0

Views: 155

Answers (1)

Alexander V.
Alexander V.

Reputation: 1538

It depends, XML is easier to work with using builtin .NET namespaces like System.Xml or System.Xml.Linq.

JSON could be better if you'll use this data in javascript or in some public game API, but it will need some third-party library to work with it like JSON.NET (it gives better json support). Also json is more lightweight then xml and large amount of data will be smaller in json.

parsing code example using linq for xml (System.Xml.Linq namespace):

var xmlString = @"<items>
  <item>
    <id>100</id>
    <name>lance</name>
    <cost>9.99</cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
  <item>
    <id>101</id>
    <name>sword</name>
    <cost>12.50</cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
</items>";

var doc = XDocument.Parse(xmlString);
var items = doc.Root.Elements("item").Select(e => new {
                                    Id = int.Parse(e.Element("id").Value), 
                                    Name = e.Element("name").Value, 
                                    Cost = decimal.Parse(e.Element("cost").Value)});

results:

results

(I'm using LinqPad for represent results here, highly recommend it for playing with linq and linq for xml)

Upvotes: 3

Related Questions