我有问题。我需要创建一个以下的xml:
<?xml version="1.0" encoding="utf-8"?>
<MyApp value="5" name="me">
</MyApp>
使用c ++代码我做了以下事情:
#include <iostream>
#include <string>
#include "tinyxml.h"
void main(){
TiXmlDocument doc;
TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "utf-8", "");
doc.LinkEndChild( decl );
TiXmlElement * root;
root = new TiXmlElement( "MyApp" );
root->SetAttribute("value","5");
root->SetAttribute("name","me");
doc.LinkEndChild( root );
doc.SaveFile( "madeByHand.xml" );
return 0;
}
我使用g ++ tinyxml.cpp tinyxmlerror.cpp和tinyxmlparser.cpp编译它。 当我想看到我创建的xml时。我有一个错误:它说它不是核心写的。我哪里错了?:)
答案 0 :(得分:5)
以防任何人需要这样的XML文件结构:
<?xml version="1.0" ?>
<Hello>Opening a new salutation
<Greeting value="5" name="me"></Greeting>
</Hello>
_
所以这是代码:
_
TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild( decl );
TiXmlElement* element = new TiXmlElement( "Hello" );
doc.LinkEndChild( element );
TiXmlText* text = new TiXmlText( "Opening a new salutation" );
element->LinkEndChild( text );
TiXmlElement* element2 = new TiXmlElement( "Greeting" );
element2->SetAttribute("value","5");
element2->SetAttribute("name","me");
element->LinkEndChild( element2 );
TiXmlText* text2 = new TiXmlText( "" );
element2->LinkEndChild( text2 );
doc.SaveFile( "madeByHand2.xml" );
_
一个选项如何使用循环添加多个元素(for / while):
_
<?xml version="1.0" ?>
<Hello>Opening a new salutation
<Greeting value="5" name="me"></Greeting>
<Greeting value="5" name="me"></Greeting>
<Greeting value="5" name="me"></Greeting>
</Hello>
_
以下是此代码:
_
TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild( decl );
TiXmlElement* element = new TiXmlElement( "Hello" );
doc.LinkEndChild( element );
TiXmlText* text = new TiXmlText( "Opening a new salutation" );
element->LinkEndChild( text );
for(long i=0; i<3; i++)
{
TiXmlElement* element2 = new TiXmlElement( "Greeting" );
TiXmlText* text2 = new TiXmlText( "" );
element2->SetAttribute("value","5");
element2->SetAttribute("name","me");
element->LinkEndChild( element2 );
element2->LinkEndChild( text2 );
}
doc.SaveFile( "madeByHand2.xml" );
答案 1 :(得分:0)
您正在尝试将C ++用作某种类型的脚本。您必须创建一个main()
函数,其中放置了生产代码。
#include <iostream>
#include <string>
#include "tinyxml.h"
void main()
{
TiXmlDocument doc;
TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "utf-8", "");
doc.LinkEndChild( decl );
TiXmlElement * root;
root = new TiXmlElement( "MyApp" );
root->SetAttribute("value","5");
root->SetAttribute("name","me");
doc.LinkEndChild( root );
doc.SaveFile( "madeByHand.xml" );
}
编译之后,你必须从命令行启动应用程序。
答案 2 :(得分:0)
可能你错过了“ #include ”tinystr.h“”?
答案 3 :(得分:0)
必须将 tinyxmlparser.cpp tinyxmlerror.cpp tinyxml.cpp tinyxml.h tinystr.cpp tinystr.h 添加到项目