我一直在为大学工作一些东西
要保存一些东西,我选择了tinyxml来做到这一点
TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", "");
doc.LinkEndChild(decl);
TiXmlElement* cm = new TiXmlElement("CocktailMachine");
doc.LinkEndChild(cm);
TiXmlElement* disp = new TiXmlElement("dispensers");
cm->LinkEndChild(disp);
TiXmlElement* cock = new TiXmlElement("cocktails");
cm->LinkEndChild(cock);
TiXmlElement* ingr = new TiXmlElement("ingredients");
cm->LinkEndChild(ingr);
for (size_t i = 0; i < dispensers.size(); i++)
{
stringstream ss;
ss << i;
string s = ss.str();
TiXmlElement* x_disp = new TiXmlElement(s.c_str());
disp->LinkEndChild(x_disp);
x_disp->SetAttribute("number", dispensers.at(i)->get_number());
if (dispensers.at(i)->get_ingredient() == NULL) {
x_disp->SetAttribute("ingredient", "NULL");
}
else {
x_disp->SetAttribute("ingredient", dispensers.at(i)->get_ingredient()->get_name().c_str());
}
}
if (cocktails.size() != 0)
for (size_t i = 0; i < cocktails.size(); i++)
{
stringstream ss;
ss << i;
string s = ss.str();
TiXmlElement* ct = new TiXmlElement(s.c_str());
cock->LinkEndChild(ct);
ct->SetAttribute("name", cocktails.at(i)->get_name().c_str());
for (size_t j = 0; j < cocktails.at(i)->get_ingredients().size(); j++)
{
stringstream ss;
ss << j;
string s = ss.str();
TiXmlElement* ct_s = new TiXmlElement(s.c_str());
ct->LinkEndChild(ct_s);
ct_s->SetAttribute("ingredient", cocktails.at(i)->get_ingredients().at(j)->get_name().c_str());
}
}
if (ingredients.size() != 0)
for (size_t i = 0; i < ingredients.size(); i++)
{
stringstream ss;
ss << i;
string s = ss.str();
TiXmlElement* x_ingr = new TiXmlElement(s.c_str());
ingr->LinkEndChild(x_ingr);
x_ingr->SetAttribute("name", ingredients.at(i)->get_name().c_str());
}
doc.SaveFile("CM.xml");
doc.Clear();
这会将一些内容保存到CM.xml中
<?xml version="1.0" ?>
<CocktailMachine>
<dispensers>
<0 number="1" ingredient="NULL" />
<1 number="2" ingredient="NULL" />
<2 number="3" ingredient="NULL" />
<3 number="4" ingredient="NULL" />
<4 number="5" ingredient="NULL" />
<5 number="6" ingredient="NULL" />
</dispensers>
<cocktails>
<0 name="Tequila Sunrise">
<0 ingredient="Tequila" />
<1 ingredient="Orange juice" />
<2 ingredient="Grenadine" />
</0>
<1 name="tq2">
<0 ingredient="Tequila" />
<1 ingredient="Orange juice" />
<2 ingredient="Grenadine" />
</1>
</cocktails>
<ingredients />
</CocktailMachine>
&#13;
当我尝试使用此
加载它时TiXmlDocument* doc = new TiXmlDocument("example1.xml");
if (!doc->LoadFile())
cout << "false";
它总是返回false
尝试加载&#34; helloworld.xml&#34;工作正常
<?xml version="1.0" ?>
<Hello>World</Hello>
&#13;
那我的xml问题在哪里?
提前谢谢 Jonny0815答案 0 :(得分:1)
问题在于:<0 number="1" ingredient="NULL" />
您不能将数字作为标记名称。
答案 1 :(得分:0)
非常感谢我解决了我的问题:D
&#34; 0不是有效的XML名称&#34;
周末愉快
OT:新来的......我可以将问题标记为&#34;已回答&#34;或者&#34;完成&#34;或者打开一个关闭请求,以便每个人都订购?