0

I have used the following codes to parse a XML file. My aim is to detect if the <Name> element is "ABC", and I will remove its <Malfunction> contents. However, my codes only allow me to read in "Name" and remove all the element tags with <Name>.

Is it possible to check if the <Name> element tag contains "ABC" and remove the contents within the <Malfunction></Malfunction> tags, including the tags themselves?

Any help is appreciated. Thanks.

.cpp:

QDomNodeList nodes = doc.elementsByTagName("Name");

while(!nodes.isEmpty())
{
    QDomNode node = nodes.at(0);
    node.parentNode().removeChild(node);
}

.xml:

<InjectedMalfunctions>
 <Malfunction>
  <Segment>ABC</Segment>
  <Name>ABC failure</Name>
  <Time>00:00:00</Time>
 </Malfunction>
 <Malfunction>
  <Segment>DEF</Segment>
  <Name>DEF failure</Name>
  <Time>00:00:00</Time>
 </Malfunction>
</InjectedMalfunctions>

Output .xml:

<InjectedMalfunctions>
 <Malfunction>
  <Segment>ABC</Segment>
  <Time>00:00:00</Time>
 </Malfunction>
 <Malfunction>
  <Segment>DEF</Segment>
  <Time>00:00:00</Time>
 </Malfunction>
</InjectedMalfunctions>

Wanted .xml:

<InjectedMalfunctions>
 <Malfunction>
  <Segment>DEF</Segment>
  <Name>DEF failure</Name>
  <Time>00:00:00</Time>
 </Malfunction>
</InjectedMalfunctions>

The following code removes all the <Malfunction> tags, instead of just the first <Malfunction> group.

Edited .cpp:

QDomNodeList nodes = doc.elementsByTagName("Name");

while(!nodes.isEmpty())
{
    QDomNode node = nodes.at(0);
    node.nodeValue().contains("ABC");
    QDomNode toRemove = node.parentNode();
    toRemove.parentNode().removeChild(toRemove);
}
1
  • Is there anybody who can advise on this? Much appreciated. Thanks.
    – Wallace
    Feb 14, 2014 at 5:44

1 Answer 1

0

Eventually this will work. Check for ABC:

node.nodeValue().contains("ABC");

remove complete

QDomnode toRemove = node.parentNode();
toRemove.parentNode().removeChild(toRemove);
1
  • I tried your mentioned codes, but it removed all the <Malfunction> tags. Am I doing anything wrong here? Please see my edited version above.
    – Wallace
    Feb 17, 2014 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.