gpt4 book ai didi

c++ - 使用 RapidXML 写入 XML

转载 作者:行者123 更新时间:2023-11-30 04:54:25 29 4
gpt4 key购买 nike

我正在尝试使用元组读取我的 vector 并将其解析为 xml 文件。写入 XML 文件有效,但他只写了最后的节点。所以我一直只得到相同的值。我发现在 for 循环之后他丢失了所有现有节点。也许我对 doc.append_node(root) 的想法是错误的?!

    #include "XmlHandle.h"
#include <rapidxml/rapidxml.hpp>
#include "rapidxml/rapidxml_print.hpp"
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <sstream>

using namespace rapidxml;

XmlHandle::WriteToXml(std::vector<std::tuple<Key, Tone>> vector)
{
xml_document<> doc;
xml_node<>* decl = doc.allocate_node(node_declaration);
//adding attributes at the top of our xml
decl->append_attribute(doc.allocate_attribute("version", "1.0"));
decl->append_attribute(doc.allocate_attribute("encoding", "utf-8"));
doc.append_node(decl);
//creating a pointer for the root note "NoteList"
xml_node<> *root = doc.allocate_node(node_element, "NoteList");

//iterating through our vector
for (std::tuple<Key, Tone> tuple : vector)
{
//creating the nodes tuple and key
xml_node<> *tuple1 = doc.allocate_node(node_element, "Tuple");
xml_node<> *key = doc.allocate_node(node_element, "Key");
//getting the char of key saving in d
char d = std::get<0>(tuple).key;
//creating a pointer on d
key->value(&d, 1);
const char *name = std::string("test").c_str();
//creating a new node element Tone
xml_node<> *ToneNode = doc.allocate_node(node_element, "Tone");
//adding the element to tuple1
tuple1->append_node(ToneNode);
//adding the note element Frequency
xml_node<> *Frequency = doc.allocate_node(node_element, "Frequency");
float FrequencyFloat = std::get<1>(tuple).frequency;
std::string FrequencyString = std::to_string(FrequencyFloat);
//setting the value from frequency
Frequency->value(FrequencyString.c_str());
tuple1->append_node(Frequency);
xml_node<> *Node = doc.allocate_node(node_element, "Node");
char * NodeValuePinter = (char*)&std::get<1>(tuple).tone;
char *charPinter = &std::get<1>(tuple).tone;
Node->value(charPinter, 1);
ToneNode->append_node(Node);
tuple1->append_node(key);
//adding tuple to our root
root->append_node(tuple1);

}
doc.append_node(root);
std::string xml_as_string;
rapidxml::print(std::back_inserter(xml_as_string), doc);
std::ofstream fileStored("file_stored.xml");
fileStored << xml_as_string;
fileStored.close();
doc.clear();
}

最佳答案

您的问题可能出在这里。

        char d = std::get<0>(tuple).key;
key->value(&d, 1);

RapidXML 存储您传递给 value() 的指针,而不是它指向的字符串。所以每次循环你的“值”都指向同一个东西 - 'd'。

您应该使用 key->value(doc.allocate_string(&d, 1)) 将字符数据的拷贝添加到键中。同样,稍后用于 node->value

Rapidxml is writing wrong characters

这绝对是排名第一的 RapidXML 陷阱。

关于c++ - 使用 RapidXML 写入 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53593933/

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