Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an XML file in C# in Unity?

Someone please help! This is really confusing for me. I can't find anyone on the internet that can explain this well enough. So here is what I need: I need someone to explain how to create an XML file in Unity. People have told me to look at a stream writer. I have searched for this but no one has given a tutorial on how to write it. I also do not know what a .NET is so please don't give me that as an answer. I have looked through the microsoft page for XML files as well but I cannot find the right answer. This is literally all I'm looking for:

I want to be able to write something like this:

<Player>

    <Level>5<\Level>  
    <Health>500<\Health>  

<\Player>

How can I make a file like this and import it to Unity? How can I make Unity read this file and extract information from something like this? Please i'm a total n00b at this whole .NET and XML thing.

like image 594
Abraham Avatar asked Jun 24 '13 22:06

Abraham


1 Answers

Say you have a Player class that looks like:

[XmlRoot]
public class Player
{
    [XmlElement]
    public int Level { get; set; }

    [XmlElement]
    public int Health { get; set; }
}

Here is a complete round-trip to get you started:

XmlSerializer xmls = new XmlSerializer(typeof(Player));

StringWriter sw = new StringWriter();
xmls.Serialize(sw, new Player { Level = 5, Health = 500 });
string xml = sw.ToString();

Player player = xmls.Deserialize(new StringReader(xml)) as Player;

xml is:

<?xml version="1.0" encoding="utf-16"?>
<Player xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Level>5</Level>
  <Health>500</Health>
</Player>

And you guess player is exactly the same as the original object we serialized.

If you want to serialize to/deserialize from files you can do something like:

using (var stream = File.OpenWrite("my_player.xml"))
{
    xmls.Serialize(stream, new Player { Level = 5, Health = 500 });
}

Player player = null;
using (var stream = File.OpenRead("my_player.xml"))
{
    player = xmls.Deserialize(stream) as Player;
}

EDIT:

IF you want exactly the XML you show:

XmlSerializer xmls = new XmlSerializer(typeof(Player));

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };
using (var stream = File.OpenWrite("my_player.xml"))
{
    using (var xmlWriter = XmlWriter.Create(stream, settings))
    {
        xmls.Serialize(xmlWriter, new Player { Level = 5, Health = 500 }, ns);
    }
}

Player player = null;
using (var stream = File.OpenRead("my_player.xml"))
{
    player = xmls.Deserialize(stream) as Player;
}
like image 128
Pragmateek Avatar answered Oct 16 '22 06:10

Pragmateek