c++ - 添加子子节点以 boost ptree

标签 c++ xml boost boost-propertytree

假设我的目标是创建以下形式的 xml:

<main>
<elements>
    <element name="elem1"><temp/>
    </element>
    <element name="elem2"><temp/>
    </element>
</elements>
</main>

我有以下代码:

ptree pt;
pt.put("main","");

ptree temp1;
temp1.put("element","");
temp1.put("element.<xmlattr>.name","elem1");
temp1.put("element.temp");

ptree temp2;
temp2.put("element","");
temp2.put("element.<xmlattr>.name","elem2");
temp2.put("element.temp");

//temp1 represents the 1st <element>...</element>
//temp2 represents the 1st <element>...</element>

//Add temp1 and temp2 to <main> under <elements>

我会假设以下会起作用:

pt.add_child("main.elements",temp1);
pt.add_child("main.elements",temp2);

但是这会生成以下 xml:

<main>
<elements>
    <element name="elem1"><temp/>
    </element>
</elements>
<elements>
    <element name="elem2"><temp/>
    </element>
<elements>
</main>

我能够通过以下形式制作我的 temp1 来获取所需的 xml 文件:

temp1.put("<xmlattr>.name","elem1");
temp1.put("temp","");
temp2.put("<xmlattr>.name","elem2");
temp2.put("temp","");
pt.add_child("main.elements.element",temp1);
pt.add_child("main.elements.element",temp2);

有没有一种方法可以使用我的初始 temp1 和 temp2 节点来获得所需的 xml 结构?

最佳答案

您的情况有点不太理想(我非常喜欢您提供的工作片段)。

这是可行的:

pt.add_child("main.elements.element", temp1.get_child("element"));
pt.add_child("main.elements.element", temp2.get_child("element"));

Live On Coliru

#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

using boost::property_tree::ptree;

int main() {
    ptree temp1;
    temp1.put("element.<xmlattr>.name","elem1");
    temp1.put_child("element.temp", {});

    ptree temp2;
    temp2.put("element.<xmlattr>.name","elem2");
    temp2.put("element.temp", "");

    //Add temp1 and temp2 to <main> under <elements>
    ptree pt;
    pt.add_child("main.elements.element", temp1.get_child("element"));
    pt.add_child("main.elements.element", temp2.get_child("element"));
    write_xml(std::cout, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 4, "utf-8"));
}

打印

<?xml version="1.0" encoding="utf-8"?>
<main>
    <elements>
        <element name="elem1">
            <temp/>
        </element>
        <element name="elem2">
            <temp/>
        </element>
    </elements>
</main>

关于c++ - 添加子子节点以 boost ptree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36021806/

相关文章:

java - java从xml文档接收子节点

c++ - boost 和图形化

c++ - 如何将一个矩阵附加到另一个矩阵的末尾? (在 C++ 中使用 Boost 库)

c++ - 具有重载运算符的无效操作数 <<

c++ - 为什么这个 if 条件无法比较负整数和正整数

c# - 从 xml 文件 C# 中获取命名空间

android - ClassCastException 安卓工作室

c++ - Windows 7中的 boost 问题

c++ - pthreads : What are the different models of pthread implemenation

c++ - 通过引用将 unique_ptr 传递给函数