如何循环 n 次,在 xml 文件中每个循环一个级别

How to loop n times, one level per loop in an xml file

本文关键字:循环 一个 文件 何循环 xml      更新时间:2023-10-16

我觉得这应该很容易,但几个小时后我仍然无法弄清楚。我尝试在谷歌上搜索它,但似乎我的大脑想要问这个问题的唯一方法是 3 行解释,这与谷歌并不真正有效。如果您有更好的表达方式,请随意编辑。

我有一个 xml 文件,这样说:

<tag1>
<tag2>
<tag3>
...
</tag3>
</tag2>
</tag1>

文档的每个父级可能有许多标签 1、标签 2 和标签 3。

使用 c++ 的 pugixml 时,我想在所选节点上执行操作。这是我想完成的伪代码,但以一种我知道是错误且不可行的方式。

for(pugi::xml_node tag1 : doc->child("tag1").children()){
//Do something with tag1
for(pugi::xml_node tag2 : doc->child("tag1").child("tag2").children()){
//Do something with tag2
for(pugi::xml_node tag3 : doc->child("tag1").child("tag2").child("tag3").children()){
//Do something with tag3
}
}

}

只是看着这个,很容易找到什么不起作用......我需要能够与doc.child((.child((.child((.child((.child((..child((.-循环内。必须为每次迭代添加 .child(( 会阻止我执行递归样式的操作,例如:

void loopXNestedTimes(int n){
if(n==0) return;
// Do my stuff
loopXNestedTimes(n-1);
}

知道我会怎么做吗?我正在使用Qt和c ++,但仍在学习两者,因此可能缺少一些语言功能可以做到这一点。

使用tag1获取tag2元素(而不是doc(,使用tag2获取tag3元素,我认为这是您缺少的关键点。

您的代码片段应如下所示:

for (pugi::xml_node tag1 : doc->child("tag1").children()){
//Do something with tag1
for (pugi::xml_node tag2 : tag1.child("tag2").children()){
//Do something with tag2
for (pugi::xml_node tag3 : tag2.child("tag3").children()){
//Do something with tag3
}
}
}