gpt4 book ai didi

c# - C# 中的 XML - hasAttribute、getAttribute 不存在吗?为什么?

转载 作者:数据小太阳 更新时间:2023-10-29 01:54:30 50 4
gpt4 key购买 nike

我正在从事一个项目,该项目要求我在单独的数据库中构建游戏的房间、元素和 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.XmlElement 具有您正在寻找的功能。您正在获取 XMLNode 的。您需要将节点转换为 XmlElement 才能获得该功能。

xmlElement = (System.Xml.XmlElement)xmlRoom;

关于c# - C# 中的 XML - hasAttribute、getAttribute 不存在吗?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13827459/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com