我有一个XML文件,其中包含几个'DATA'
标记。我想将每个'DATA'
的内容写入单独的 JSON文件。目前,我已经根据XML文件创建了documentElement
。任何帮助将不胜感激。
我的XML文件如下:
<?xml version='1.0' encoding='UTF-8'?>
<data>
<student>
<name>Alice</name>
<mark>
<language>96</language>
<maths>45</maths
</mark>
</student>
<name>Bob</name>
<mark>
<language>80</language>
<maths>75</maths
</mark>
</student>
</data>
预期输出: file1.json->
{
"name":"Alice",
"mark":[
{"language":96},
{"maths":45}
]
}
答案 0 :(得分:0)
为了将数据存储到JSON,您需要使用QJsonDocument
您可以按名称获取所有XML标记。
例如:
// In your code:
writeXMLElements(oXMLDomELement, "name", "myfilepath");
// then use these functions to iterate the DOM elements and to store the data in JSON file
void AQWireXQtDomParser::wirteXMLElements(const QDomElement & oXMLContent, const QString & oTagName, const QString & oFileName)
{
QDomNodeList oXMLElementsLis = oXMLContent.elementsByTagName(oTagName);
for (int i = 0; i<oXMLElementsLis.size();++i )
{
QDomNode oNode = oXMLElementsLis.at(i);
writeData(oNode.toElement(), QString("filpath_%1").arg(i)); // store in new file name
}
}
void writeData(const QDomElement & oXMLContent, const QString & oFileName)
{
QJsonDocument oDocument;
QJsonObject oObj;
// store the XML content to JSON object.
oObj.insert("xml_content", oXMLContent.text()); // key, value
oDocument.setObject(oObj);
// save JSON content to a local file
QFile oJsonFile(oFileName);
oJsonFile.open(QFile::WriteOnly);
oJsonFile.write(oDocument.toJson());
}