我正在开展一个项目,要求我在一个单独的数据库中构建游戏的房间,物品和NPC.我选择了XML,但有些东西阻止我在C#代码中正确解析XML.我究竟做错了什么?
我的错误是这些:
System.xml.xmlnode does not contain a definition for HasAttribute
Run Code Online (Sandbox Code Playgroud)
(这GetAttribute也适用)并且没有接受'HasAttribute'接受第一个类型参数的扩展方法System.Xml.XmlNode?
这也是GetParentNode我的最后一行
string isMoveableStr = xmlRoom.GetAttribute("isMoveable");
Run Code Online (Sandbox Code Playgroud)
不知何故:
the name xmlRoom does not exist in the current context
Run Code Online (Sandbox Code Playgroud)
这是方法:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
System.Xml.XmlElement具有您要查找的功能.你正在获得XMLNode.您需要将节点强制转换为XmlElement才能获得该功能.
xmlElement = (System.Xml.XmlElement)xmlRoom;
Run Code Online (Sandbox Code Playgroud)