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

前端 未结 1 832
野性不改
野性不改 2020-12-30 16:00

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 expla

相关标签:
1条回答
  • 2020-12-30 16:30

    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;
    }
    
    0 讨论(0)
提交回复
热议问题