【发布时间】:2016-03-05 16:18:41
【问题描述】:
为了好玩,我正在尝试开发一个简单的 RPG。我希望我的游戏使用 XML 文件,以便让玩家轻松自定义游戏。
我有一个 Race 类和一个带有所有种族的静态列表的 raceManager 类。 我首先使用 XmlAttributs (XmlRoot, XmlElement...) 和默认序列化程序将可播放的比赛写入 Xml。
XmlSerializer xs = new XmlSerializer(managedList.GetType());
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
xs.Serialize(fs, managedList);
}
它有效,但在我的种族课上,我有技能清单,可用武器...... 默认的序列化程序会生成包含这些类的所有属性的数组。
由于我只想要每个对象的单个实例,因此我开始实现 IXmlSerializable 接口以仅写入 id 并在读取时检索对象。
现在 Xml 文件几乎就像我想要的那样:
<?xml version="1.0"?>
<ArrayOfRace xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Race>
<NameMale>Human</NameMale>
...
<ArmorsTypesAllowed>
<ArmorType>Cloth</ArmorType>
<ArmorType>Leather</ArmorType>
<ArmorType>Metal</ArmorType>
</ArmorsTypesAllowed>
</Race>
<Race>
<NameMale>Dwarf</NameMale>
...
</Race>
...
但我再也看不懂了:'(
我使用我的经理方法(以前效果很好):
protected static List<T> ReadFile(string filePath)
{
List<T> ManagedList = new List<T>();
XmlSerializer xs = new XmlSerializer(ManagedList.GetType());
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
ManagedList = (List<T>)xs.Deserialize(fs);
}
return ManagedList;
}
使用了 ReadXml 方法,但返回一个包含 1 个元素(最后一个)的列表。 看起来整个文件(包含列表)被发送到我的 ReadXml,它假设只读取该列表的一个元素。
public void ReadXml(XmlReader reader)
{
while(!reader.EOF)
{
if(reader.NodeType == XmlNodeType.Element)
{
switch(reader.Name)
{
case "NameMale":
NameMale = reader.ReadElementContentAsString();
break;
case "NameFemale":
NameFemale = reader.ReadElementContentAsString();
break;
...
default:
reader.Read();
break;
}
}
else
{
reader.Read();
}
}
}
我想我或许应该阻止读者。所以我添加了以下代码,但它并没有解决我的问题(只有第一场比赛是用这个检索的)
if(reader.NodeType == XmlNodeType.EndElement && reader.Name == "Race")
{
return;
}
提前谢谢你,对不起我的英语不好。
编辑:这是一个带有控制台应用程序的最小但完整的示例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace StackOverFlowQuestion
{
class Program
{
static void Main(string[] args)
{
if (!File.Exists(Manager.FilePath))
{
Manager.WriteFile(Manager.FilePath, Manager.GenerateMyClass());
}
Manager.Initialize();
foreach (MyClass mc in Manager.ListOfMyClass)
{
Console.WriteLine("A:" + mc.A);
Console.WriteLine("B:" + mc.B);
foreach(AnotherClass ac in mc.MyList)
{
Console.WriteLine("Item ID: " + ac.Id);
}
}
Console.ReadLine();
}
}
public class MyClass : IXmlSerializable
{
public string A { get; set; }
public string B { get; set; }
public List<AnotherClass> MyList { get; set; }
public MyClass() { }
public MyClass(string a, string b, List<AnotherClass> list)
{
this.A = a;
this.B = b;
this.MyList = list;
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
while (!reader.EOF)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "A":
A = reader.ReadElementContentAsString();
break;
case "B":
B = reader.ReadElementContentAsString();
break;
case "MyList":
MyList = new List<AnotherClass>();
reader.Read();
break;
case "ListItem":
string s = reader.ReadElementContentAsString();
MyList.Add(Manager.ListOfAnotherClass.Single(x => x.Id == s));
break;
default:
reader.Read();
break;
}
}
else
{
reader.Read();
}
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("A", A);
writer.WriteElementString("B", B);
writer.WriteComment("Only Id must be serialize !");
writer.WriteStartElement("MyList");
if (MyList != null)
{
foreach (AnotherClass ac in MyList)
{
writer.WriteElementString("ListItem", ac.Id);
}
}
writer.WriteEndElement();
}
}
public class AnotherClass
{
public string Id { get; set; }
public string someProperty { get; set; }
public AnotherClass(string id, string prop)
{
this.Id = id;
this.someProperty = prop;
}
}
class Manager
{
public static List<MyClass> ListOfMyClass { get; set; }
public static string FilePath = "MyXmlFile.xml";
//This list should be from another XML file.
private static List<AnotherClass> _listofAnotherClass;
public static List<AnotherClass> ListOfAnotherClass
{
get
{
if (_listofAnotherClass == null)
{
_listofAnotherClass = GenerateAnotherClass();
}
return _listofAnotherClass;
}
}
public static void Initialize()
{
ListOfMyClass = ReadFile(Manager.FilePath);
}
public static List<MyClass> ReadFile(string filePath)
{
List<MyClass> ManagedList = new List<MyClass>();
XmlSerializer xs = new XmlSerializer(ManagedList.GetType());
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
ManagedList = (List<MyClass>)xs.Deserialize(fs);
}
return ManagedList;
}
public static void WriteFile(string filePath, List<MyClass> managedList)
{
XmlSerializer xs = new XmlSerializer(managedList.GetType());
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
xs.Serialize(fs, managedList);
}
}
public static List<MyClass> GenerateMyClass()
{
List<MyClass> list = new List<MyClass>();
MyClass m;
m = new MyClass("ValueA", "ValueB", new List<AnotherClass>(Manager.ListOfAnotherClass.Where(x => x.Id == "Id1" || x.Id == "Id3")));
list.Add(m);
m = new MyClass("ValA", "ValB", new List<AnotherClass>(Manager.ListOfAnotherClass.Where(x => x.Id == "Id2" || x.Id == "Id3")));
list.Add(m);
return list;
}
public static List<AnotherClass> GenerateAnotherClass()
{
List<AnotherClass> anotherList = new List<AnotherClass>();
anotherList.Add(new AnotherClass("Id1", "Prop1"));
anotherList.Add(new AnotherClass("Id2", "Prop2"));
anotherList.Add(new AnotherClass("Id3", "Prop3"));
return anotherList;
}
}
}
【问题讨论】:
-
您的问题很复杂,但由于缺少许多课程,因此也不完整。您能否将其归结为minimal but complete example 的问题,我们可以将其复制并粘贴到 Visual Studio 中并进行测试?
-
如果您尝试编辑 XML 文件中的特定节点而不加载或写入整个文件,那么 XML 并不是真正为此而设计的。见In C#, is there a way to add an XML node to a file on disk WITHOUT loading it first? 或blogs.msdn.com/b/mfussell/archive/2005/02/12/371546.aspx
-
我用一个最小但完整的例子编辑了我的问题。我不是要编辑节点,我想了解为什么在实现 IXmlSerializable 接口后,编写一个列表工作但读取它只返回 1 个元素。
-
看来你的问题已经解决了,我就不去调试了。你是对的,如果你的
WriteXml()读取的元素太多或太少,它会弄乱后续的反序列化,因为XmlReader定位错误。查看codeproject.com/Articles/43237/… 和stackoverflow.com/questions/279534/… 获取如何正确操作的指南。
标签: c# xml ixmlserializable