【发布时间】:2012-11-29 10:20:49
【问题描述】:
我正在开展一个项目,该项目需要我在单独的数据库中构建游戏的房间、物品和 NPC。我选择了 XML,但是有些东西阻止了我在 C# 代码中正确解析 XML。我做错了什么?
我的错误是:
System.xml.xmlnode does not contain a definition for HasAttribute
(这也适用于GetAttribute)并且没有扩展方法接受'HasAttribute' 接受System.Xml.XmlNode 类型的第一个参数?
这也适用于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.xmlnode 不包含 HasAttribute 的定义(这也适用于 GetAttribute),并且没有接受“HasAttribute”的扩展方法接受 system.xml.xmlnode 类型的第一个参数?
-
老实说,
System.Xml对象既陈旧又烦人。我会为此使用System.Xml.Linq。 (或者根本不使用 XML) -
如果我们假设我的知识“不够出色”:System.Xml.Linq 对我的代码有什么要求?
-
Linq to XML:以
XDocument或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 - 很棒的例子,但对我们这里的朋友来说,它一定看起来像古希腊。