QXmlStreamWriter модификация файла xml

Рейтинг: 1Ответов: 1Опубликовано: 13.02.2023

Пытаюсь модифицировать xml код. Мне нужно добавить в узел код с сохранением предыдущего.

XML файл в который мне нужно добавить код имеет вид:

<office:automatic-styles>
  <style:style style:name="c10" style:family="text">
    <style:text-properties fo:font-family="TimesNewRoman" fo:font-size="12pt" fo:text-transform="none" fo:letter-spacing="0pt" style:text-underline-type="none" style:text-line-through-type="none" style:text-underline-style="none"/>
  </style:style>
  <style:style style:name="TB28.33" style:family="table-cell">
    <style:table-cell-properties fo:border="0.75pt solid #000000" fo:padding-top="0.75pt" fo:padding-bottom="0.75pt" fo:padding-left="0.48pt" />
  </style:style>
</office:automatic-styles>

Мне нужно добавить код между <office:automatic-styles> </office:automatic-styles>

Для этого сделал:

QString xmlCode(
            "\n"
            "<style:page-layout-properties fo:page-width=\"21.59cm\" fo:page-height=\"27.94cm\" style:num-format=\"1\" style:print-orientation=\"portrait\" fo:margin-top=\"2cm\" fo:margin-bottom=\"2cm\" fo:margin-left=\"2cm\" fo:margin-right=\"2cm\" style:writing-mode=\"lr-tb\" style:layout-grid-color=\"#c0c0c0\" style:layout-grid-lines=\"44\" style:layout-grid-base-height=\"0.55cm\" style:layout-grid-ruby-height=\"0cm\" style:layout-grid-mode=\"none\" style:layout-grid-ruby-below=\"false\" style:layout-grid-print=\"true\" style:layout-grid-display=\"true\" style:footnote-max-height=\"0cm\">"
            "\n"
            "<style:footnote-sep style:width=\"0.018cm\" style:distance-before-sep=\"0.101cm\" style:distance-after-sep=\"0.101cm\" style:line-style=\"none\" style:adjustment=\"left\" style:rel-width=\"25%\" style:color=\"#000000\"/>"
            "\n"
            "</style:page-layout-properties>"
            "\n"
            "<style:header-style>"
            "\n"
            "<style:header-footer-properties fo:min-height=\"0cm\" fo:margin-left=\"0cm\" fo:margin-right=\"0cm\" fo:margin-bottom=\"0.499cm\"/>"
            "\n"
            "</style:header-style>"
            "\n"
            "<style:footer-style>"
            "\n"
            "<style:header-footer-properties fo:min-height=\"0cm\" fo:margin-left=\"0cm\" fo:margin-right=\"0cm\" fo:margin-top=\"0.499cm\"/>"
            "\n"
            "</style:footer-style>"
            "\n"
           );

QFile file("/media/usb0/folder/content.xml");
if (!file.open(QIODevice::ReadWrite))
    return;
QXmlStreamWriter xmlWriter(&file);
xmlWriter.setAutoFormatting(true);
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement("office:automatic-styles");
xmlWriter.writeCharacters(xmlCode);
xmlWriter.writeEndElement();

Но получил:

<office:automatic-styles>
&lt;style:page-layout-properties fo:page-width=&quot;21.59cm&quot; fo:page-height=&quot;27.94cm&quot; style:num-format=&quot;1&quot; style:print-orientation=&quot;portrait&quot; fo:margin-top=&quot;2cm&quot; fo:margin-bottom=&quot;2cm&quot; fo:margin-left=&quot;2cm&quot; fo:margin-right=&quot;2cm&quot; style:writing-mode=&quot;lr-tb&quot; style:layout-grid-color=&quot;#c0c0c0&quot; style:layout-grid-lines=&quot;44&quot; style:layout-grid-base-height=&quot;0.55cm&quot; style:layout-grid-ruby-height=&quot;0cm&quot; style:layout-grid-mode=&quot;none&quot; style:layout-grid-ruby-below=&quot;false&quot; style:layout-grid-print=&quot;true&quot; style:layout-grid-display=&quot;true&quot; style:footnote-max-height=&quot;0cm&quot;&gt;
&lt;style:footnote-sep style:width=&quot;0.018cm&quot; style:distance-before-sep=&quot;0.101cm&quot; style:distance-after-sep=&quot;0.101cm&quot; style:line-style=&quot;none&quot; style:adjustment=&quot;left&quot; style:rel-width=&quot;25%&quot; style:color=&quot;#000000&quot;/&gt;
&lt;/style:page-layout-properties&gt;
&lt;style:header-style&gt;
&lt;style:header-footer-properties fo:min-height=&quot;0cm&quot; fo:margin-left=&quot;0cm&quot; fo:margin-right=&quot;0cm&quot; fo:margin-bottom=&quot;0.499cm&quot;/&gt;
&lt;/style:header-style&gt;
&lt;style:footer-style&gt;
&lt;style:header-footer-properties fo:min-height=&quot;0cm&quot; fo:margin-left=&quot;0cm&quot; fo:margin-right=&quot;0cm&quot; fo:margin-top=&quot;0.499cm&quot;/&gt;
&lt;/style:footer-style&gt;
</office:automatic-styles>ell-properties fo:padding-top="0.75pt" fo:padding-bottom="0.75pt" fo:padding-left="0.48pt"/>
    </style:style>
    <style:style style:name="Table5" style:family="table">
      <style:table-properties table:border-model="collapsing"/>
    </style:style>

Ответы

▲ 0Принят

Вы получаете данный вывод т.к. QXmlStreamWriter::writeCharacters экранирует символы <, >, & и " как &lt;, &gt, &amp; и &quot.

Для вставки текста без изменений можно использовать QXmlStreamWriter::writeDTD. Но лучше вставлять xml-данные через QXmlStreamWriter::writeStartElement и QXmlStreamWriter::writeAttribute. Иначе вам скорее всего не нужен QXmlStreamWriter как таковой.

А если вы хотите добавлять изменения в существующий xml документ, то вам нужно использовать QXmlStreamWriter в паре с QXmlStreamReader. В противном случае QXmlStreamWriter будет просто перезаписывать данные в начале вашего файла. Как пример:

QFile file("/media/usb0/folder/content.xml");
if (!file.open(QIODevice::ReadOnly))
    return -1;
QXmlStreamReader reader(&file);
QByteArray data; //Буффер для данных
QXmlStreamWriter writer(&data);
writer.setAutoFormatting(true);
while (!reader.isEndDocument())
{

    if (reader.tokenType() != QXmlStreamReader::Invalid) {
        writer.writeCurrentToken(reader); //Копируем текущий элемент
    } else {
        qDebug() << reader.errorString();
    }
    //Условие для добавления
    if (reader.name() == "office:automatic-styles" && reader.isStartElement() ) { 
        //Пишем новые элементы
        //...
    }
    reader.readNext(); //Читаем следующий элемент
}
file.close();
if (!file.open(QIODevice::WriteOnly))
    return -1;
file.write(data);
file.close();