unity 中编写xml

前端之家收集整理的这篇文章主要介绍了unity 中编写xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


谁能帮帮我,这太让我头疼了!网上还没有人能很好地解释我的问题。

我所需要的是:我需要有个人来解释怎样在Unity中创建XML文件。人们告诉我去看看stream writer。我搜了一下,但是没有人给出教程。我也不知道.NET是什么,所以不要再回答我这个了。我已经看微软页关于XML文件的信息,也没有找到正确的解决方法。这是我想要找的:

我想要写出这样的东西:

1
2
3
4
5
6
<Player>
<Level>5<\Level>
<Health>500<\Health>
<\Player>

我怎样才能制作出这样的文件并且导入到Unity里?怎样才能让Unity读取这个文件,并像这样从某些东西里抽取信息?我对.NET和XML完全不懂。

答案:

Pragmateek

假设你有这样的 Player class:

1
2
3
4
5
6
7
8
9
[XmlRoot]
public class Player
{
[XmlElement]
public int Level { get; set; }
[XmlElement]
public int Health { get; set; }
}

这是让你开始的完整过程:

1
2
3
4
5
6
7
8
9
10
11
12
13
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" ?>
<Level>5</Level>
<Health>500</Health>
</Player>

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

如果你想从文件序列化或反序列化,你可以这样做:

1
2
3
4
5
6
7
8
9
10
using ( var stream = File.OpenWrite( "my_player.xml" ))
{
xmls.Serialize(stream,Health = 500 });
}
Player player = null ;
using ( var stream = File.OpenRead( "my_player.xml" ))
{
player = xmls.Deserialize(stream) as Player;
}

EDIT:

如果你想要完全展现XML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
XmlSerializer xmls = 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,Health = 500 },ns);
}
}
Player player = var stream = File.OpenRead( "my_player.xml" ))
{
player = xmls.Deserialize(stream) as Player;
}

猜你在找的XML相关文章