0

我写了一个小程序通讯录,联系人存储在xml文件中。这是代码的一部分

void new_engine::main_window::write_to_db(const QString& n, const QString& s)
{
    QFile m_db_file(m_db_path);
    QString t("User");
    m_db_file.open(QIODevice::Append);
    QXmlStreamWriter wxml(&m_db_file);
    wxml.setAutoFormatting(true);
    if(m_size == 1)
    {
        wxml.writeStartDocument();
        wxml.writeStartElement("Persons");
    }
    wxml.writeStartElement(t);
    QString id = QString::number(m_size);
    wxml.writeAttribute("id", id);
    wxml.writeTextElement("Name", n);
    wxml.writeTextElement("Surname", s);
    wxml.writeEndElement();
    wxml.writeEndDocument();
    m_db_file.close();
}

但问题是标签文件的第一次接触后关闭。这是结果

<?xml version="1.0" encoding="UTF-8"?>
<Persons>
    <User id="1">
        <Name>das</Name>
        <Surname>vcvx</Surname>
    </User>
</Persons>

<User id="2">
    <Name>eqwevxcv</Name>
    <Surname>xcvxcx</Surname>
</User>

<User id="3">
    <Name>das</Name>
    <Surname>dasdasd</Surname>
</User>

但一定是这样

<Persons>
    <User id="1">
        <Name>das</Name>
        <Surname>vcvx</Surname>
    </User>

    <User id="2">
        <Name>eqwevxcv</Name>
        <Surname>xcvxcx</Surname>
    </User>

    <User id="3">
        <Name>das</Name>
        <Surname>dasdasd</Surname>
    </User>
</Persons>

我们怎样才能做到这一点,在每个新记录之后都必须更改文档结束?

4

1 回答 1

1

这是一个例子:

void write_to_db(QXmlStreamWriter& writer, QString id, QString name, QString surname)
{
  writer.writeStartElement("User");
  writer.writeAttribute(QXmlStreamAttribute("id", id));

  writer.writeTextElement("Name", name);
  writer.writeTextElement("Surname", surname);

  writer.writeEndElement();
}

// This can be a file, or whatever iodevice your heart desires.
QString out;
QXmlStreamWriter writer(&out);
writer.writeStartDocument();
writer.writeStartElement("Persons");

write_to_db(writer, "1", "das", "vcvx");
write_to_db(writer, "2", "das", "vcvx");
write_to_db(writer, "3", "das", "vcvx");

writer.writeEndElement(); // Close <persons> tag
writer.writeEndDocument();

输出(使用 QXmlStreamWriter::setAutoFormatting/Indent):

<?xml version="1.0"?>
<Persons>
 <User id="1">
  <Name>das</Name>
  <Surname>vcvx</Surname>
 </User>
 <User id="2">
  <Name>das</Name>
  <Surname>vcvx</Surname>
 </User>
 <User id="3">
  <Name>das</Name>
  <Surname>vcvx</Surname>
 </User>
</Persons>
于 2013-06-20T16:19:09.690 回答