简体   繁体   English

XmlStreamWriter

[英]XmlStreamWriter

I am a newbie to Qt and I want to update(add new nodes and attributes) a xml file using Qt 4 and QxmlStreamwriter, but Append open mode sets the cursor in file after the enddocument line... 我是Qt的新手,我想使用Qt 4和QxmlStreamwriter更新(添加新的节点和属性)一个xml文件,但是Append开放模式将光标设置在enddocument行之后的文件中...

Is there anyway to achieve that using QXmlStreamWriter? 无论如何,可以使用QXmlStreamWriter实现这一目标吗? If so, please give me an example code 如果是这样,请给我一个示例代码

You will need to re-write the file with the extra nodes. 您将需要使用额外的节点重新编写文件。 The stream interface ( QXmlStreamReader / QXmlStreamWriter ) is more complex to use to do this than the DOM ( QDomDocument ) interface, but has the benefit of lower memory requirements. 与DOM( QDomDocument )接口相比,使用流接口( QXmlStreamReader / QXmlStreamWriter )执行此操作更为复杂,但是具有降低内存需求的优点。

With the DOM interface you work with an in-memory representation of the XML document. 使用DOM接口,您可以使用XML文档的内存表示形式。 With the stream interface you may need to build and maintain your own representation. 使用流接口,您可能需要构建和维护自己的表示形式。

Sample code for the stream interface: 流接口的示例代码:

QFile inputFile("in.xml");
if (! inputFile.open(QIODevice::ReadOnly))
  // error handling
QFile outputFile("out.xml");
if (! outputFile.open(QIODevice::WriteOnly))
  // error handling

QXmlStreamReader inputStream(&inputFile);
QXmlStreamWriter outputStream(&outputFile);

while (! inputStream.atEnd())
{
   inputStream.readNext();
   // manipulation logic goes here
   outputStream.writeCurrentToken(inputStream);
}

Sample code for the DOM interface: DOM接口的示例代码:

QFile inputFile("in.xml");
if (! inputFile.open(QIODevice::ReadOnly))
  // error handling

QDomDocument doc;
if (! doc.setContent(&inputFile))
  // error handling

// manipulation logic goes here

QFile outputFile("out.xml");
if (! outputFile.open(QIODevice::WriteOnly))
  // error handling

outputFile.write(doc.toByteArray());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM