2014-12-08 83 views
1

我可以把我的XML文档文件为对象:获得来自rapidxml孩子计数:的XMLNode获得随机子节点

if(exists("generators.xml")) { //http://stackoverflow.com/a/12774387/607407 
    rapidxml::file<> xmlFile("generators.xml"); // Open file, default template is char 

    xml_document<> doc;    // character type defaults to char 
    doc.parse<0>(xmlFile.data());; // 0 means default parse flags 
    xml_node<> *main = doc.first_node(); //Get the main node that contains everything 
    cout << "Name of my first node is: " << doc.first_node()->name() << "\n"; 

    if(main!=NULL) { 
     //Get random child node? 
    } 
} 

我想选择一个随机的子节点从主要对象。我的XML看起来像这样(version with comments):

<?xml version="1.0" encoding="windows-1250"?> 
<Stripes> 
    <Generator> 
    <stripe h="0,360" s="255,255" l="50,80" width="10,20" /> 
    </Generator> 
    <Generator> 
    <loop> 
     <stripe h="0,360" s="255,255" l="50,80" width="10,20" /> 
     <stripe h="0,360" s="255,255" l="0,0" width="10,20" /> 
    </loop> 
    </Generator> 
</Stripes> 

我要挑随机<Generator>进入。我觉得让孩子数将是一个办法做到这一点:

//Fictional code - **all** methods are fictional! 
unsigned int count = node->child_count(); 
//In real code, `rand` is not a good way to get anything random 
xmlnode<> *child = node->childAt(rand(0, count)); 

我怎样才能得到孩子计数和孩子从rapidxml节点偏移?

回答

1

RapidXML使用链接列表存储DOM树,正如您所知,它不是可直接编入索引的。

所以你基本上需要自己实现这两个方法,遍历节点的子节点。像这样(未经测试)的代码。

int getChildCount(xmlnode<> *n) 
{ 
    int c = 0; 
    for (xmlnode<> *child = n->first_node(); child != NULL; child = child->next_sibling()) 
    { 
    c++; 
    } 
    return c; 
} 

getChildAt显然是相似的。

+0

是的。我已经实现了为给定节点返回儿童的'std :: vector'的函数。我只是希望有一个内置的功能。 – 2014-12-11 13:01:58

+0

@TomášZato - 只是发现你可能正在使用'rapidxml_utils',它有一个辅助函数'count_children',它执行相同的操作。虽然没有'child_at'功能。 – Roddy 2014-12-11 14:21:38

+1

因为我发现了随机孩子,[孩子数量实际上是不必要的信息](http://math.stackexchange.com/a/1058547/60941)。 – 2014-12-11 14:26:41