谁能帮帮我,这太让我头疼了!网上还没有人能很好地解释我的问题。
我所需要的是:我需要有个人来解释怎样在Unity中创建XML文件。人们告诉我去看看stream writer。我搜了一下,但是没有人给出教程。我也不知道.NET是什么,所以不要再回答我这个了。我已经看微软页关于XML文件的信息,也没有找到正确的解决方法。这是我想要找的:
我想要写出这样的东西:
我怎样才能制作出这样的文件并且导入到Unity里?怎样才能让Unity读取这个文件,并像这样从某些东西里抽取信息?我对.NET和XML完全不懂。
答案:
假设你有这样的 Player class:
@H_502_13@ 1 @H_502_13@ 2 @H_502_13@ 3 @H_502_13@ 4 @H_502_13@ 5 @H_502_13@ 6 @H_502_13@ 7 @H_502_13@ 8 @H_502_13@ 9 |
@H_502_13@
@H_502_13@
[XmlRoot]
@H_502_13@
public class Player
@H_502_13@
{
@H_502_13@
[XmlElement]
@H_502_13@
public int Level { get; set; }
@H_502_13@
@H_502_13@
[XmlElement]
@H_502_13@
public int Health { get; set; }
@H_502_13@
}
|
这是让你开始的完整过程:
@H_502_13@ 1 @H_502_13@ 2 @H_502_13@ 3 @H_502_13@ 4 @H_502_13@ 5 @H_502_13@ 6 @H_502_13@ 7 @H_502_13@ 8 @H_502_13@ 9 @H_502_13@ 10 @H_502_13@ 11 @H_502_13@ 12 @H_502_13@ 13 |
@H_502_13@
@H_502_13@
XmlSerializer xmls =
new
XmlSerializer(
typeof
(Player));
@H_502_13@
@H_502_13@
StringWriter sw =
new
StringWriter();
@H_502_13@
xmls.Serialize(sw,
new
Player { Level = 5,Health = 500 });
@H_502_13@
string xml = sw.ToString();
@H_502_13@
@H_502_13@
Player player = xmls.Deserialize(
new
StringReader(xml)) as Player;
@H_502_13@
xml is:
@H_502_13@
<?xml version=
"1.0"
encoding=
"utf-16"
?>
@H_502_13@
<Player xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd=
"http://www.w3.org/2001/XMLSchema"
>
@H_502_13@
<Level>5</Level>
@H_502_13@
<Health>500</Health>
@H_502_13@
</Player>
|
player 和我们序列化的原始对象完全一样。
如果你想从文件序列化或反序列化,你可以这样做:
@H_502_13@ 1 @H_502_13@ 2 @H_502_13@ 3 @H_502_13@ 4 @H_502_13@ 5 @H_502_13@ 6 @H_502_13@ 7 @H_502_13@ 8 @H_502_13@ 9 @H_502_13@ 10 |
@H_502_13@
@H_502_13@
using (
var
stream = File.OpenWrite(
"my_player.xml"
))
@H_502_13@
{
@H_502_13@
xmls.Serialize(stream,Health = 500 });
@H_502_13@
}
@H_502_13@
@H_502_13@
Player player =
null
;
@H_502_13@
using (
var
stream = File.OpenRead(
"my_player.xml"
))
@H_502_13@
{
@H_502_13@
player = xmls.Deserialize(stream) as Player;
@H_502_13@
}
|
EDIT:
如果你想要完全展现XML:
@H_502_13@ 1 @H_502_13@ 2 @H_502_13@ 3 @H_502_13@ 4 @H_502_13@ 5 @H_502_13@ 6 @H_502_13@ 7 @H_502_13@ 8 @H_502_13@ 9 @H_502_13@ 10 @H_502_13@ 11 @H_502_13@ 12 @H_502_13@ 13 @H_502_13@ 14 @H_502_13@ 15 @H_502_13@ 16 @H_502_13@ 17 @H_502_13@ 18 |
@H_502_13@
@H_502_13@
XmlSerializer xmls =
typeof
(Player));
@H_502_13@
@H_502_13@
XmlSerializerNamespaces ns =
new
XmlSerializerNamespaces();
@H_502_13@
ns.Add(
""
,
""
);
@H_502_13@
XmlWriterSettings settings =
new
XmlWriterSettings { OmitXmlDeclaration =
true
,Indent =
true
};
@H_502_13@
using (
var
stream = File.OpenWrite(
"my_player.xml"
))
@H_502_13@
{
@H_502_13@
using (
var
xmlWriter = XmlWriter.Create(stream,settings))
@H_502_13@
{
@H_502_13@
xmls.Serialize(xmlWriter,Health = 500 },ns);
@H_502_13@
}
@H_502_13@
}
@H_502_13@
@H_502_13@
Player player =
var
stream = File.OpenRead(
"my_player.xml"
))
@H_502_13@
{
@H_502_13@
player = xmls.Deserialize(stream) as Player;
@H_502_13@
}
|