c++rapidxml无法正确使用已保存的xml_document

c++ rapidxml cant use saved xml_document properly

本文关键字:保存 xml document c++rapidxml      更新时间:2023-10-16

我正在尝试将一些xml字符串解析为xml_document,并将xml_documents保存为一个变量以供进一步使用。在解析之后,xml_document就可以直接使用了,但我无法从其他方法访问它。

以下是示例代码:XML.h

//
// Created by artur on 18.07.18.
//
#ifndef PLSMONITOR_XML_H
#define PLSMONITOR_XML_H
#include <rapidxml/rapidxml.hpp>
class XML {
public:
XML();
void print();
private:
rapidxml::xml_document<> _store_xml;
};
#endif //PLSMONITOR_XML_H

XML.cpp

//
// Created by artur on 18.07.18.
//
#include "XML.h"
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
XML::XML() {
std::string str{"<Store>"
" <Field1>1</Field1>"
"</Store>"
""};
char* cstr = new char[str.size() + 1];
strcpy (cstr, str.c_str());
_store_xml.parse<0>(cstr);
// this prints the 1
cout <<_store_xml.first_node("Store")->first_node("Field1")->value() << endl;
delete [] cstr;
}
void XML::print() {
// this exits with Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
cout <<_store_xml.first_node("Store")->first_node("Field1")->value() << endl;
}
int main(int argc, char *argv[]) {
cout << "Test of XML" << endl;
XML xml{};
xml.print();
}

在构造函数中使用xml_document是可以的,但在print方法中使用它会崩溃。这是控制台输出:

XML测试1

进程结束,退出代码为139(被信号11中断:sigsegov(

有人知道如何正确使用rapidxml文档并保存xml结构以供进一步使用吗?

感谢

问题是,正如文档中所述,在处理文档之前处理xml字符串违反了xml_document::parse方法的约定

字符串必须在文档的生存期内保持。

xml_document不复制字符串内容以避免额外的内存分配,因此字符串必须保持活动状态。您可以将字符串设为类字段。还要注意,对于C++17,字符串类中有一个非常量限定的data方法,因此不需要分配另一个临时缓冲区。