简体   繁体   English

RapidXML加载xml文件

[英]RapidXML loading xml files

I cannot return the loadings from the xml. 我无法从xml返回加载。 Here is the code: 这是代码:

RapidXML xml loader RapidXML xml加载程序

vector<char*> ParseFanbeamGeometry(char* fileName)
{
    xml_document<> doc;
    xml_node<> * root_node;
    // Read the xml file into a vector
    ifstream theFile (fileName);
    vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());
    buffer.push_back('\0');
    // Parse the buffer using the xml file parsing library into doc 
    doc.parse<0>(&buffer[0]);
    // Find our root node
    root_node = doc.first_node("FanbeamGeometrySettings");

    vector<char*> fambeamGeometry;
    // Iterate over the fangeometry
    for (xml_node<> * fanGeometry_node = root_node->first_node("FanGeometry"); fanGeometry_node; fanGeometry_node = fanGeometry_node->next_sibling())
    {      
        try
        {
            fambeamGeometry.push_back(fanGeometry_node->first_attribute("geometry")->value());
            fambeamGeometry.push_back(fanGeometry_node->first_attribute("D")->value());
        }
        catch (exception &e)
        {
            e.what();
        }
    }

    return fambeamGeometry;

}

main function 主功能

int _tmain(int argc, _TCHAR* argv[])
{
    char* fangeofile = "D:\\Projects\\fanbeam\\tools\\rapidxml-1.13\\GeometrySettings.xml";

    vector<char*> fambeamGeometry = ParseFanbeamGeometry(fangeofile);

    float D = atof(fambeamGeometry[1])*N;

    getchar();
    return 0;
}

xml file xml文件

<?xml version="1.0"?>
<FanbeamGeometrySettings>
  <FanGeometry geometry="EquiDistance" D="2"/>
</FanbeamGeometrySettings>

The fambeamGeometry properly loads "EquiDistance" and "2", but when it is returned from ParseFanbeamGeometry() to main, the value becomes some weird values, like -18 and -2. fambeamGeometry正确加载了“ EquiDistance”和“ 2”,但是当它从ParseFanbeamGeometry()返回到main时,该值变成了一些奇怪的值,例如-18和-2。

Any suggestions? 有什么建议么? I have no idea why. 我不知道为什么。 How to let the xml loader return what it loads? 如何让xml加载程序返回加载的内容? Thanks. 谢谢。

Your function ParseFanbeamGeometry is returning a vector of pointers, but the data that they point to will be invalid once buffer gets destructed as the function returns. 您的函数ParseFanbeamGeometry返回的是指针向量,但是一旦函数返回时buffer被破坏,它们指向的数据将无效。

The correct approach, as you've realized is to pass back std::string s instead. 您已经意识到,正确的方法是传回std::string That's the idiomatic approach in C++ anyway. 无论如何,这是C ++中的惯用方法。

vector<std::string> ParseFanbeamGeometry(const std::string &fileName)

Use vector<std::string> instead of 使用vector<std::string>代替

vector<char*> 

then, use string.c_str() to convert string to 然后,使用string.c_str()string转换为

char*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM