gpt4 book ai didi

c++ - 使用 C++ boost 属性树在多个标签上具有相同属性的 XML

转载 作者:行者123 更新时间:2023-11-30 03:31:20 25 4
gpt4 key购买 nike

是否可以使用 C++ boost::property_tree 生成以下 XML?

<tests>
<test id="12" age="7">123</test>
<test id="15" age="8">1rr</test>
<test id="52" age="71">1qe3</test>
<test id="72" age="5">1d5</test>
</tests>

我用过:

test.add("<xmlattr>.id", 12);
test.add("<xmlattr>.age", 8);
tests.add_child("test", test);
//Called multiple times

它产生了一个错误:

Attribute id Redefined

最佳答案

您需要创建单独的 test 元素:

Live On Coliru

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

using boost::property_tree::ptree;

int main() {
struct { int id, age; std::string value; } data[] = {
{ 12, 7, "123" },
{ 15, 8, "1rr" },
{ 52, 71, "1qe3" },
{ 72, 5, "1d5" },
};

ptree tests;

for (auto& item : data) {
ptree test;
test.add("<xmlattr>.id", item.id);
test.add("<xmlattr>.age", item.age);
test.put_value(item.value);
tests.add_child("test", test);
};

boost::property_tree::ptree pt;
pt.add_child("tests", tests);
write_xml(std::cout, pt, boost::property_tree::xml_writer_make_settings<std::string>(' ', 4));
}

打印:

<?xml version="1.0" encoding="utf-8"?>
<tests>
<test id="12" age="7">123</test>
<test id="15" age="8">1rr</test>
<test id="52" age="71">1qe3</test>
<test id="72" age="5">1d5</test>
</tests>

关于c++ - 使用 C++ boost 属性树在多个标签上具有相同属性的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44271079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com