C ++ RapidXML获得相同类型的兄弟?

时间:2013-03-02 02:15:37

标签: c++ xml rapidxml

因此,在RapidXML中,我正在尝试遍历我的文件以从一些tileset节点获取数据:

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...

你可能会说,问题是什么?好吧,在RapidXML中,next_sibling()函数可选匹配名称:

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.

因此,如果找不到名称的节点,则无论如何都会返回下一个兄弟节点。这是我的程序中的一个问题,我只是简单地不想要额外的迭代。我认为这是愚蠢的,但无论如何。有没有办法让 ONLY 遍历我的tileset节点?

2 个答案:

答案 0 :(得分:2)

“可选地匹配节点名称” - 在参数中是可选的。如果传递名称字符串,但未找到,则返回值为零。

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;
}

答案 1 :(得分:0)

我也有这个问题,我使用这个小修改作为解决方法,按预期工作。

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
}