2012-08-02 22 views
1

我在c中使用Rapidxml兄弟節點&不同兄弟姐妹的可變數量++到一個XML文件檢查用於Rapidxml

讀取I具有基於以下示例中兩個問題

<?xml version="1.0" encoding="utf-8"?> 
<rootnode version="1.0" type="example"> 
    <childnode1 entry="1"> 
    <evendeepernode attr1="cat" attr2="dog"/> 
    <evendeepernode attr1="lion" attr2="wolf"/> 
    </childnode1> 
    <childnode2 entry="1"> 
    </childnode2> 
</rootnode> 

1-如果相同類型的兄弟姐妹(evendeepernode)的數量是可變的。我如何檢查它?

2-如果有不同的兄弟姐妹(例如childnode1 & childnode2),並有數目是可變的(例如可以有多於1級childnode1的和/或可以有多於1級childnode2的或它們中的一個在可能不存在所有)。我該如何檢查?

回答

0

好的我還沒有編譯下面的代碼,但它應該足夠準確,可以根據您的需要進行修改。它至少應該說明你可以用於你的目的的方法和功能。可能有更好的方法,但是如果你沒有其他答覆,這將做你需要的。

對於喜歡1-你介紹我使用類似於以下

xml_document<> doc;  
doc.parse<0>(xml_buffer); // parse your string 
xml_node<>* rootnode = doc.first_node("rootnode"); // Get first node 
xml_node<>* childnode1 = rootnode->first_node("childnode1");  // childnode1 

if (childnode1 != NULL) { 
    // get first deeper node and loop over them all 
    int number_of_siblings = 0; 
    xml_node<>* deepernode = childnode1->first_node(); 
    while (deepernode != NULL) { 
     // Do processing on this node 

     // Your processing code here.... 

     // now get the next deepernode in this current level of nesting 
     // pointer will be NULL when no more siblings 
     deepernode = deepernode->next_sibling(); 
     number_of_siblings++; 
    } 
    // Your xml had number_of_sibling nodes at this level 
} 

代碼對於你的問題2 - 您可以通過兄弟節點在childnode1級使用同一種while循環的循環問題。如果您需要檢查兄弟的名字,你可以使用

string strNodeName = "childnode2"; 
if (current_node->name() == strNodeName) { 
    // current node is called childnode2 - do your processing. 
} 

如果你不需要檢查節點名稱,只是用它來遍歷所有子節點下的根節點

xml_document<> doc;  
doc.parse<0>(xml_buffer); // parse your string 
xml_node<>* rootnode = doc.first_node("rootnode"); // Get first node 
xml_node<>* childnode = rootnode->first_node();  // get first childnode 
int child_node_count = 0; 
while (childnode != NULL) { 
    // Do processing on this node 

    // get sibling of current node (if there is one)  
    childnode = childnode->next_sibling(); 
    child_node_count++; 
} 
// child_node_count is now the number of child nodes under rootnode. 
+0

嘿感謝了很多尋求幫助。如果數據存儲在名爲example.xml的文件中,還有1個問題。如何打開該文件併爲C++定義輸入流,如「cin」 – 2012-08-04 14:38:59

+0

查看iostream文件打開對象,如fstream – mathematician1975 2012-08-04 15:20:48

+0

我在嘗試類似這樣的操作\t xml_document <> doc; ifstream myfile(「map.osm」); doc.parse <0>(myfile); 並收到以下錯誤在這行 多個標記 \t - 參數無效「考生:無效 \t解析(字符*)」 \t - 符號「解析」無法解析 – 2012-08-04 15:57:58