You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于pugixml手动实现递归XML遍历(代码已修复可运行)

手动实现PugiXML递归遍历XML节点

虽然PugiXML提供了pugi::xml_node::traverse方法可直接遍历XML文件,但为探究遍历的实现原理,我尝试用递归函数手动实现该功能。最初版本仅能解析XML的第一层节点,问题出在无法正确判断当前节点是否包含子节点(next_siblings返回无效值),经过修复后代码已能正常运行。

实现代码

// TODO: use std::ostringstream instead of std::string
void MyClass::recursive(const pugi::xml_node& start, std::string& output) 
{
    // Check for invalid node
    if (!start.first_child() || (!start.next_sibling() && start.parent() != start.parent())) {
        return;
    }
    // Process the current node
    for (auto node : start.children()) {
        output += node.name();
        output += "\n";
        for (auto attribute : node.attributes()) {
            output += "Attribute Name : ";
            output += attribute.name();
            output += ", Attribute Value = ";
            output += attribute.value();
            output += " ";
        }
        output += "\n";
        const char* PCDATA = node.child_value();
        output += PCDATA == "" ? "[no pcdata]"
                               : PCDATA;
        if (node.first_child()) {
            recursive(node, output);
        }
        else {
            recursive(node.next_sibling(), output);
        }
    }
}

示例XML文件

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <child1>
        <sub name="attr1">value</sub>
        <sub name="attr2">value</sub>
        <sub name="attr3">value</sub>
    </child1>
    <child2>
        <sub name="attr1">value</sub>
        <sub name="attr2">value</sub>
        <sub name="attr3">value</sub>
    </child2>
    <child3>
        <sub name="attr1">value</sub>
        <sub_with_children>
            <child1 name="[]">value</sub>
            <child2 name="[]">value</sub>
            <child3 name="[]">value</sub>
        </sub_with_children>
    </child3>
    <child4>
        <sub name="attr1">value</sub>
        <sub name="attr2">value</sub>
    </child4>
</root>

内容的提问来源于stack exchange,提问作者Chadribleu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:48:22