我有以下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
答案 0 :(得分:2)
您不应将文件名传递给文档构造函数和LoadFile()
。根据TinyXML网站上的示例,尝试从后者中省略它。
如果仍然无效,请打印doc->ErrorDesc()
(可能还有ErrorRow和ErrorCol)。
阅读文档:http://www.grinninglizard.com/tinyxmldocs/classTiXmlDocument.html
答案 1 :(得分: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>