I have a big xml file that I need to remove specific nodes from

QString filename= QFileDialog::getOpenFileName(this, "Choose File");
if(filename.isEmpty())
   return;

QFile file(filename);

if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
   return;

QDomDocument xmlBOM;
xmlBOM.setContent(&file);

QDomNodeList roots = xmlBOM.elementsByTagName("TEST_SCE");

for ( int i = 0; i < roots.count(); i++ )
{

   QDomElement node = roots.at(i).toElement();
   QDomNodeList noderoots = node.elementsByTagName("TEST_SET");
   for ( int j = 0; j < noderoots.count(); j++ )
   {

       QDomElement node2 = noderoots.at(j).toElement();
       QDomNodeList noderoots2 = node2.elementsByTagName("TEST");
       int count = 0;
       for ( int k = 0; k < noderoots2.count(); k++ )
       {
           QDomNode node3 = noderoots2.at(k);
           unsigned int startFreq = Node3.toElement().firstChild().toElement().attribute("start","0").toUInt();
           if (startFreq >= 20000000)
           {
               count++;
               //delete this test element
               node3.parentNode().removeChild(node3);
               k--;
           }
       }
   }   
}   
QByteArray xml = xmlBOM.toByteArray();   
file.write(xml);   
file.close();

And I've checked the noderoots2 count, it does go down while I'm removing the child node, however when I save the file, there is no change in the file.

Here is an example of the xml file

<VERIFICATION Location="Here" Created="11h28 2021/07/15">
  <TEST_SCE>
    <TEST_SET>
        <TEST>
            <FREQUENCY_RANGE_Hz start="2000000" stop="19000000" step="1000000"/>
        </TEST>
        <TEST>
            <FREQUENCY_RANGE_Hz start="20000000" stop="30000000" step="1000000"/>
        </TEST>
        <TEST>
            <FREQUENCY_RANGE_Hz start="31900000" stop="54000000" step="1000000"/>
        </TEST>            
    </TEST_SET>
  </TEST_SCE>
</VERIFICATION>
1

There are 1 best solutions below

0
On

There was nothing wrong with the XML code. The error was with the file handling.

I edited the code as follows:

  1. Closed the file after xmlBOM.setContent(&file);
  2. Opened the file when saving the changes
   if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly)) {
       return;
   }

   QByteArray xml = xmlBOM.toByteArray();
   file.write(xml);
   file.close();