tinyxml2
tinyxml2 copied to clipboard
No <?xml version="1.0"?> declaration at beginning of output files
I've noticed that my output XML documents work fine but do not begin with <?xml version="1.0"?>
Since a well-formatted XML document requires , should an output XML document always include this header by default?
Here is an example of my code which does not include the <?xml version="1.0"?>
header:
Creating Document
tinyxml2::XMLDocument* MainWindow::create_XML()
{
tinyxml2::XMLDocument *xmlDoc = new tinyxml2::XMLDocument;
tinyxml2::XMLNode *root = xmlDoc->NewElement("root");
xmlDoc->InsertFirstChild(root);
tinyxml2::XMLElement *save_date = xmlDoc->NewElement("save_date");
root->InsertEndChild(save_date);
QString date = QDate::currentDate().toString();
save_date->SetText(date.toStdString().c_str());
......
......
......
Saving Document
bool MainWindow::on_actionSave_triggered()
{
tinyxml2::XMLDocument *xmlDoc = create_XML();
QString save_file_path = QFileDialog::getSaveFileName(this,
"Save File",
QDir::toNativeSeparators(QDir::currentPath()),
"XML Files (*.xml)\n"
"All Files (*.*)");
if (save_file_path.isEmpty())
return false;
if (!save_file_path.contains(".xml"))
save_file_path += ".xml";
xmlDoc->SaveFile(save_file_path.toStdString().c_str());
delete xmlDoc;
xmlDoc = nullptr;
return true;
}
You forgot to add a delcaration item (which can be e.g. ).
So your code should looks like:
void create_XML()
{
tinyxml2::XMLDocument *xmlDoc = new tinyxml2::XMLDocument;
auto declaration = xmlDoc->NewDeclaration();
tinyxml2::XMLNode *root = xmlDoc->NewElement("root");
xmlDoc->InsertFirstChild(declaration);
xmlDoc->InsertAfterChild(declaration, root);
tinyxml2::XMLElement *save_date = xmlDoc->NewElement("save_date");
root->InsertEndChild(save_date);
save_date->SetText("2022-01-01");
xmlDoc->SaveFile("/tmp/myxml.xml");
delete xmlDoc;
}
the result will be:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<save_date>2022-01-01</save_date>
</root>
@leethomason So I think this bug could be closed.