我对使用 XML 在我实际管理的 C# 中定义对象非常陌生,但必须有更好的方法。
我的游戏数据库的数据是在几个 XML 文件中构建的,这是其中一个更复杂的文件,因为我用它来测试所有地方
<GameData xmlns:NSW="Napivo.StarWars">
<!-- Ships -->
<!-- AITroopAccelerator -->
<Asset Type="ShipDescription">
<Name>AITroopAccelerator</Name>
<Asset Type="SpriteAnimation">
<Name>\Ships\AITroopAccelerator\1.png</Name>
<Name>\Ships\AITroopAccelerator\2.png</Name>
<Name>\Ships\AITroopAccelerator\3.png</Name>
<Name>\Ships\AITroopAccelerator\2.png</Name>
<Speed>150</Speed>
</Asset>
<Asset Type="WeaponGroup" Num ="0">
<Weapon Name ="Missile" Angle ="0" X ="0" Y ="0"> </Weapon>
<Asset Type="WeaponGroup" Num ="1">
<Weapon Name ="NegativeEnergyFlare" Angle ="180" X ="0" Y ="0"> </Weapon>
</Asset>
<Weapon Name ="Lightning" Angle ="0" X ="0" Y ="0"> </Weapon>
</Asset>
<Asset Type="WeaponGroup" Num ="2">
<Weapon Name ="FastLazer" Angle ="-10" X ="0" Y ="0"> </Weapon>
<Weapon Name ="FastLazer" Angle ="+10" X ="0" Y ="0"> </Weapon>
<Weapon Name ="Ion" Angle ="-90" X ="0" Y ="0"> </Weapon>
</Asset>
<Asset Type="Armory">
<Resource Type ="Energy" Ammout ="-1000" Recharge ="0.2"></Resource>
<Resource Type ="Missile" Ammout ="-10" Recharge ="0"></Resource>
</Asset>
<HullStrength>100</HullStrength>
<ShieldStrength>100</ShieldStrength>
<ColorMask>\Ships\AITroopAccelerator\ColorMask.png</ColorMask>
<Scale>1</Scale>
这是我需要编写的代码来制作这个xml文件的正面或反面......
private void ReadShipDescription(XmlNode node)
{
ShipDescription sd = new ShipDescription();
XmlNodeList NL = node.ChildNodes;
foreach (XmlNode n in NL)
{
Console.WriteLine("{0} = {1}", n.Name, n.Value);
if (n.Name == "Name")
{
sd.Name = n.InnerText;
}
if (n.Name == "Scale")
{
sd.Scale = float.Parse(n.InnerText);
}
if (n.Name == "HullStrength")
{
sd.HullStrength = float.Parse(n.InnerText);
}
if (n.Name == "ShieldStrength")
{
sd.ShieldStrength = float.Parse(n.InnerText);
}
if (n.Attributes != null)
{
foreach (XmlAttribute a in n.Attributes)
{
if ((n.Name == "Asset") && (a.Name == "Type") && (a.Value == "SpriteAnimation"))
{
sd.HullAnimation = ReadSpriteAnimation(n);
}
if ((n.Name == "Asset") && (a.Name == "Type") && (a.Value == "WeaponGroup"))
{
sd.WeaponGroups.Add(ReadWeaponGroup(n));
}
if ((n.Name == "Asset") && (a.Name == "Type") && (a.Value == "Armory"))
{
XmlNode childnode = n.FirstChild;
while (childnode != null)
{
ResourceDescription rd = ReadResource(childnode);
if (rd.Ammount < 0)
{
rd.Ammount = float.PositiveInfinity;
}
sd.Armory.Add(rd);
childnode = childnode.NextSibling;
}
}
Console.WriteLine("{0} = {1}", a.Name, a.Value);
}
}
if (n.Name == "ColorMask")
{
sd.ColorMask = n.InnerText;
}
}
ShipDescriptions.Add(sd.Name, sd);
}
这对我来说似乎不对。
谁能把我送到可以学习如何将对象直接从 XML 读取到类或结构中的地方?
希望我不会对这一票投太多反对票。
谢谢。