谁能帮帮我,这太让我头疼了!网上还没有人能很好地解释我的问题。
我所需要的是:我需要有个人来解释怎样在Unity中创建XML文件。人们告诉我去看看stream writer。我搜了一下,但是没有人给出教程。我也不知道.NET是什么,所以不要再回答我这个了。我已经看微软页关于XML文件的信息,也没有找到正确的解决方法。这是我想要找的:
我想要写出这样的东西:
1
2
3
4
5
6
|
<Player>
<Level>5<\Level>
<Health>500<\Health>
<\Player>
|
我怎样才能制作出这样的文件并且导入到Unity里?怎样才能让Unity读取这个文件,并像这样从某些东西里抽取信息?我对.NET和XML完全不懂。
答案:
假设你有这样的 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"
?>
<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 和我们序列化的原始对象完全一样。
如果你想从文件序列化或反序列化,你可以这样做:
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;
}
|