C++ RapidXML get sibling of the same type?

大城市里の小女人 提交于 2019-12-25 06:51:17

问题


So, in RapidXML, I'm trying to loop through my file to get the data from some tileset nodes:

rapidxml::xml_node<> *root_node = doc.first_node("map");
for(rapidxml::xml_node<> *tileset = root_node->first_node("tileset");
    tileset != 0; tileset = tileset->next_sibling("tileset"))
{
    // Iteration stuff...

You're probably saying, what's the problem? Well, in RapidXML, the next_sibling() function optionally matches the name:

xml_node<Ch>* next_sibling(const Ch *name=0, std::size_t name_size=0, bool
   case_sensitive=true) const;

Gets next sibling node, optionally matching node name. Behaviour is undefined 
   if node has no parent. Use parent() to test if node has a parent.

Hence, if a node is not found with the name, it'll just return the next sibling regardless. This is a problem in my program, and I just plain don't want the extra iteration. I think this is stupid, but whatever. Is there a way to make it ONLY iterate through my tileset nodes?


回答1:


"optionally matching node name" - As in the parameter is optional. If you pass a name string, and it is not found you will get a return value of zero.

xml_node<Ch> *next_sibling(const Ch *name = 0, std::size_t name_size = 0, bool case_sensitive = true) const
{
    assert(this->m_parent);     // Cannot query for siblings if node has no parent
    if (name)
    {
        if (name_size == 0)
            name_size = internal::measure(name);
        for (xml_node<Ch> *sibling = m_next_sibling; sibling; sibling = sibling->m_next_sibling)
            if (internal::compare(sibling->name(), sibling->name_size(), name, name_size, case_sensitive))
                return sibling;
        return 0;
    }
    else
        return m_next_sibling;
}



回答2:


I also had this problem and I used this small modification as a workaround, which works as intended.

rapidxml::xml_node<> *root_node = doc.first_node("map");
for(rapidxml::xml_node<> *tileset = root_node->first_node("tileset");
    tileset != 0;
    tileset = tileset->next_sibling())
{
    if(strcmp(tileset->name(), "tileset")!=0)
        continue;

    //TODO: the usual loop contents
}


来源:https://stackoverflow.com/questions/15169943/c-rapidxml-get-sibling-of-the-same-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!