Deleting specific subchild of XML file



  • In my xml file i have a node whose subchilder have 2 attributes, i have to delete 1 whole subchild while considering only 1 attribute. I have given an example below

    XML file:

    <UMG>
      <UMG_VAR Name="ABC" Value="1"></UMG_VAR>
      <UMG_VAR Name="ABC1" Value="2"></UMG_VAR>
      <UMG_VAR Name="ABC2" Value="3"></UMG_VAR>
      <UMG_VAR Name="ABC3" Value="4"></UMG_VAR>
      <UMG_VAR Name="ABC4" Value="5"></UMG_VAR>
    </UMG>
    

    I have to delete the whole subchild with only "Name" attribute, because Value can be changed.

    My code until now:

    void::MainWindow::XML()
    {
        QString path = ui->lineEdit_7->text();
    
        qDebug()<<path;
        if(!file.exists() )
            {
            qDebug() << "Check your file";
        }
        QDomDocument dom;
        dom.setContent(&file);
        QDomNodeList nodes = dom.elementsByTagName("UMG");
    
        QDomNodeList loc_childNodes = nodes.at(0).childNodes();
    
        for(int i=0; i<loc_childNodes.count(); i++)
        {
            QDomNode node = loc_childNodes.at(i);
            qDebug() << node.attributes().namedItem("Name").nodeValue(); // I get all Name attributes.
    

    last qDebug gives me all "Name" attributes. I am stuck at deleting the subchild with using this information.

    edit:
    Expected xml file:

    <UMG>
      <UMG_VAR Name="ABC" Value="1"></UMG_VAR>
      <UMG_VAR Name="ABC1" Value="2"></UMG_VAR>
      <UMG_VAR Name="ABC2" Value="3"></UMG_VAR>
      <UMG_VAR Name="ABC3" Value="4"></UMG_VAR>
    </UMG>
    

  • Moderators

    I'm not sure what you're asking. Do you want to remove an attribute or a whole node? Could you post an xml result you would like to get?



  • @Chris-Kawa Edited, added expected result, i want to delete the last subchild(just an example)


  • Moderators

    Removing last UMG_VAR node would look something like this:

    QDomNodeList umgVars = dom.elementsByTagName("UMG_VAR");
    if(!umgVars.isEmpty())
    {
        QDomNode lastElem = umgVars.at(umgVars.size() - 1);
        lastElem.parentNode().removeChild(lastElem);
    }
    


  • Thanks! worked.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.