检查 Rapidxml 中可变数量的同级节点和不同的同级节点

check for variable number of sibling nodes & different siblings in Rapidxml

本文关键字:节点 Rapidxml 检查      更新时间:2023-10-16

我在c++中使用Rapidxml读取xml文件

基于以下示例,我有两个问题

<?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-如果相同类型的同级节点(evendepernode)的数量是可变的。我该怎么查?

2-如果存在不同的兄弟姐妹(例如,childnode1&childnode2)并且数量是可变的(例如,可以有多于1个childnode1和/或可以有多于一个childnode2,或者其中一个可能根本不存在)。我该怎么查?

好的,我还没有编译下面的代码,但它应该足够准确,可以根据您的需要进行修改。它至少应该说明可以用于您的目的的方法和功能。也许有更好的方法,但如果你没有得到其他回复,这将满足你的需要。

对于像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-您可以使用相同类型的while循环来循环子节点1级别的同级节点。如果你需要检查兄弟姐妹的名字,你可以使用

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

如果您不需要检查节点名称,只需使用它在rootnode下的所有子节点上循环即可

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.