2014-12-08 87 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