以防万一有人需要这样的 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" );