0

我正在尝试在我的应用程序中创建一个函数,该函数可以通过 xml 文件中的属性加载到对象中。我想使用 TinyXML2,因为我听说它对于游戏来说非常简单快捷。

目前我有以下xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<Level>
    <Pulsator starttime="0" type="0" higherradius="100" lowerradius="10" time="60" y="500" x="300" bpm="60"/>
</Level>

Pulsator 的每个属性都是我的 Pulsator 类中的一个变量。我使用 followign 函数来导入我的 Pulsators 并将它们添加到对象向量中。

void Game::LoadLevel(string filename)
{
    tinyxml2::XMLDocument level;
    level.LoadFile(filename.c_str());
    tinyxml2::XMLNode* root = level.FirstChild();
    tinyxml2::XMLNode* childNode = root->FirstChild();

    while (childNode)
    {
        Pulsator* tempPulse = new Pulsator();
        float bpm;
        float type;
        std::string::size_type sz;

        tinyxml2::XMLElement* data = childNode->ToElement();
        string inputdata = data->Attribute("bpm");
        bpm = std::stof(inputdata, &sz);

        if (type == 0)
        {
            tempPulse->type = Obstacle;
            tempPulse->SetColor(D2D1::ColorF(D2D1::ColorF::Black));
        }
        if (type == 1)
        {
            tempPulse->type = Enemy;
            tempPulse->SetColor(D2D1::ColorF(D2D1::ColorF::Red));
        }
        if (type == 2)
        {
            tempPulse->type = Score;
            tempPulse->SetColor(D2D1::ColorF(D2D1::ColorF::Green));
        }
        else
        {
            tempPulse->type = No_Type;
        }

        objects.push_back(tempPulse);
    }
}

每次我到达根节点时,它都会错误地加载并且子节点变为空。我是在错误地使用它还是我的 XML 文件有问题?

4

1 回答 1

0

代码没有正确指定它想要的孩子。您需要第一个 XMLElement,而不是第一个子元素。为此,请在获取 childNode 时使用以下代码:

tinyxml2::XMLElement* childNode = root->FirstChildElement();

这可以为您节省以后的演员阵容。(您不需要也不应该使用 ToElement())。

于 2014-09-19T18:36:40.223 回答