5

有人请帮忙!这对我来说真的很困惑。我在互联网上找不到任何人可以很好地解释这一点。所以这就是我需要的:我需要有人解释如何在 Unity 中创建 XML 文件。人们告诉我看一个流作家。我已经搜索过了,但没有人给出如何编写它的教程。我也不知道.NET 是什么,所以请不要给我这个答案。我也浏览了 Microsoft 页面中的 XML 文件,但找不到正确的答案。这就是我正在寻找的所有内容:

我希望能够写出这样的东西:

<Player>

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

<\Player>

如何制作这样的文件并将其导入 Unity?如何让 Unity 读取此文件并从中提取信息?请在整个 .NET 和 XML 方面,我完全是 n00b。

4

1 回答 1

15

假设您有一个Player类,如下所示:

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

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

这是一个完整的往返旅程,可以帮助您入门:

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是:

<?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>

而且你猜player和我们序列化的原始对象完全一样。

如果要从文件序列化/反序列化,可以执行以下操作:

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;
}

编辑:

如果您想要您显示的 XML:

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;
}
于 2013-06-24T23:32:13.620 回答