2

我有以下 xml 文件:

<?xml version="1.0" ?>
<Hello>World</Hello>

它与我的所有其他文件位于同一目录中。

我使用这个源文件方法来解析它:

void Character::assign_xml(const char * filename) //Assign xml takes the name of the xml file as a string, and uses it to parse the file's nodes.
{
    TiXmlDocument * doc = new TiXmlDocument(filename);

    bool loadOkay = doc->LoadFile(filename);



    if (loadOkay)
    {
        printf("\n%s\n", filename);
    }
    else
    {
        printf("%s does not work.", filename);
    }

    delete doc;

}

然而,当我将字符串传递给它时,我的 loadOkay 变量等于 false。为什么是这样?

我的输出产生以下内容:

Starting /home/holland/code/qt/chronos-build-desktop/chronos...
id01.xml does not work.Failed to open file/home/holland/code/qt/chronos-build-desktop/chronos exited with code 0

作为 strace 提供:

futex(0x84579c, FUTEX_WAKE_PRIVATE, 2147483647) = 0
open("id01.xml", O_RDONLY)              = -1 ENOENT (No such file or directory)
fstat64(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb773e000
write(1, "id01.xml does not work.Failed to"..., 42id01.xml does not work.Failed to open file) = 42
4

2 回答 2

2

您不应将文件名同时传递给文档构造函数和LoadFile(). 根据 TinyXML 网站上的示例,尝试从后者中省略它。

如果它仍然不起作用,请打印出来doc->ErrorDesc()(可能还有 ErrorRow 和 ErrorCol)。

并阅读文档:http ://www.grinninglizard.com/tinyxmldocs/classTiXmlDocument.html

于 2011-08-25T00:17:47.353 回答
0

在该页面上有一个使用 TinyXML 进行解析的小示例:Tiny XML Parser Example

这是带有微小修改的示例:

#include "tinyxml.h" 

#include <iostream>
#include <string>
using namespace std; 

void Parcours( TiXmlNode* node, int level = 0 )
{
    cout << string( level*3, ' ' ) << "[" << node->Value() << "]";
    if ( node->ToElement() )
    {
        TiXmlElement* elem = node->ToElement();
        for ( const TiXmlAttribute* attr = elem->FirstAttribute(); attr; attr = attr->Next() )
            cout << " (" << attr->Name() << "=" << attr->Value() << ")";
    }
    cout << "\n";     

    for( TiXmlNode* elem = node->FirstChild(); elem; elem = elem->NextSibling() )
        Parcours( elem, level + 1 );
} 

int main( int argc, char* argv[] )
{
    TiXmlDocument doc("C:/test.xml" );
    bool loadOkay = doc.LoadFile();
    if ( !loadOkay ) {
        cerr << "Could not load test file. Error='" << doc.ErrorDesc() << "'. Exiting.\n";
        return 1;
    } 
    Parcours( doc.RootElement() );
}

您可以使用您的 xml 文件(它对我有用)或这样的 xml 文档进行尝试:

<Parent>
    <Child1 test="program" />    
    <Child2>
        <Node number="123456789" />      
    </Child2>
    <Child3>        
        <Hello World="!!!" />
    </Child3>    
</Parent>
于 2014-03-13T17:21:42.013 回答