[英]How do I read nested xml using rapidxml
我正在嘗試使用RapidXML來解析如下所示的xml內容:
<?xml version="1.0" ?>
<!DOCTYPE open-psa>
<open-psa>
<define-gate name="top" >
<or>
<gate name="g1" />
<gate name="g2" />
</or>
</define-gate>
<define-basic-event name="e1">
<exponential>
<parameter name="lambda1" />
<mission-time />
</exponential>
</define-basic-event>
<define-parameter name="lambda1">
<lognormal-deviate>
<float value="2.0e-5" />
<float value="3" />
<float value="0.95" />
</lognormal-deviate>
</define-parameter>
</open-psa>
我可以使用以下代碼訪問所有直接子代以open-psa
cout << "Importing fault tree...\n" ;
xml_document<> doc;
xml_node<> * root_node;
char* node_name;
// Read the xml file into a buffer
ifstream theFile ("SmallTree.xml");
vector<char> buffer((istreambuf_iterator<char>(theFile)),
istreambuf_iterator<char>());
buffer.push_back('\0');
// Parse the buffer
doc.parse<0>(&buffer[0]);
// Find the root node
root_node = doc.first_node("open-psa");
// Iterate over all child nodes
for (xml_node<> * node = root_node->first_node(); node; node = node->next_sibling())
{
node_name = node->name();
if (strcmp(node_name, "define-gate" ) == 0)
{
cout << node->name() << ", ";
cout << node->first_attribute("name")->value() << endl;
}
else if (strcmp(node_name, "define-basic-event" ) == 0)
{
cout << node->name() << ", ";
cout << node->first_attribute("name")->value() << endl;
}
else if (strcmp(node_name, "define-parameter" ) == 0)
{
cout << node->name() << ", ";
cout << node->first_attribute("name")->value() << endl;
}
}
現在我被困住了。 我如何訪問嵌套在例如define-gate name =“ top”中的元素。您可能會猜到一個實際的.xml文件可能包含大量的Gates,基本事件,參數等,但我不認為我可以采用任何特定順序。
每個節點有first_node()函數,所以里面的if
在您確定節點名稱,你可以做的另一種循環,開頭xml_node<>* child = node->first_node()
並繼續child = child->next_sibling()
。
謝謝你的提示。 經過一些實驗,我想到了以下幫助函數來讀取“門”。 條件語句嵌套得很深,因此是輔助程序。 作品! 再一次感謝你的幫助!
void readGate(xml_node<>* node)
{
//
char* gname ;
xml_node<>* gtype = node->first_node();
if (gtype != 0)
{
gname = gtype->name();
if (strcmp(gname, "and" ) == 0)
{
// found an "and" gate, read children
cout << " " << gname << endl;
xml_node<>* gin = gtype->first_node();
while (gin != 0)
{
cout << " " << gin->name() << ", ";
cout << " " << gin->first_attribute("name")->value();
cout << endl;
gin = gin->next_sibling();
}
}
else if (strcmp(gname, "or" ) == 0)
{
// found an "or" gate, read children
cout << " " << gname << endl;
xml_node<>* gin = gtype->first_node();
while(gin != 0)
{
cout << " " << gin->name() << ", ";
cout << " " << gin->first_attribute("name")->value();
cout << endl;
gin = gin->next_sibling();
}
}
}
}
node-> next_sibling()使您在XML文檔中處於同一級別的下一個節點。 如果要進入“節點”的內部節點,請使用first_node():
xml_node<>* nodeInternal = node->first_node();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.