我正在处理一个项目,需要将游戏的房间、物品和NPC建立在一个单独的数据库中。我选择了XML格式,但是我的C#代码无法正确解析XML文件。请问我做错了什么?
我的错误如下:
System.xml.xmlnode does not contain a definition for HasAttribute
(这也适用于
GetAttribute
)没有扩展方法接受类型为System.Xml.XmlNode
的第一个参数的'HasAttribute'?
对于GetParentNode
也是如此,还有我的最后一行。
string isMoveableStr = xmlRoom.GetAttribute("isMoveable");
某种方式进行:
the name xmlRoom does not exist in the current context
这里是方法:
public void loadFromFile()
{
XmlDocument xmlDoc = new XmlDocument(); // create an xml document object in memory.
xmlDoc.Load("gamedata.xml"); // load the XML document from the specified file into the object in memory.
// Get rooms, NPCs, and items.
XmlNodeList xmlRooms = xmlDoc.GetElementsByTagName("room");
XmlNodeList xmlNPCs = xmlDoc.GetElementsByTagName("npc");
XmlNodeList xmlItems = xmlDoc.GetElementsByTagName("item");
foreach(XmlNode xmlRoom in xmlRooms) { // defaults for room:
string roomID = "";
string roomDescription = "this a standard room, nothing special about it.";
if( !xmlRoom.HasAttribute("ID") ) //http://msdn.microsoft.com/en-us/library/acwfyhc7.aspx
{
Console.WriteLine("A room was in the xml file without an ID attribute. Correct this to use the room");
continue; //skips remaining code in loop
} else {
roomID = xmlRoom.GetAttribute("id"); //http://msdn.microsoft.com/en-us/library/acwfyhc7.aspx
}
if( xmlRoom.hasAttribute("description") )
{
roomDescription = xmlRoom.GetAttribute("description");
}
Room myRoom = new Room(roomDescription, roomID); //creates a room
rooms.Add(myRoom); //adds to list with all rooms in game ;)
} foreach(XmlNode xmlNPC in xmlNPCs)
{ bool isMoveable = false;
if( !xmlNPC.hasAttribute("id") )
{
Console.WriteLine("A NPC was in the xml file, without an id attribute, correct this to spawn the npc");
continue; //skips remaining code in loop
}
XmlNode inRoom = xmlNPC.getParentNode();
string roomID = inRoom.GetAttribute("id");
if( xmlNPC.hasAttribute("isMoveable") )
{
string isMoveableStr = xmlRoom.GetAttribute("isMoveable");
if( isMoveableStr == "true" )
isMoveable = true;
}
}
}
System.Xml
的对象古老且令人讨厌。我会使用System.Xml.Linq
来处理这个问题。(或者干脆不使用 XML) - ChaosPandionXDocument
或XElement
实例开始:var xdoc = XDocument.Load("gamedata.xml"); var xRooms = xdoc.Descendants("room");
。然后,例如,您可以使用以下内容替换整个循环以检查缺少的ID:if (xRooms.Any(xRoom => (string)xRoom.Attribute("ID") == null)) {Console.WriteLine("A room was in the xml file without an ID attribute...");} else {var rooms = xRooms.Select(xRoom => new Room(xRoom.Attribute("description"), (int)xRoom.Attribute("ID"))).ToList();}
。 - Zev Spitz