2

How do I remove a child with a specific attribute? I´m using c++/libxml2. My attempt so far (in the example I want to remove child node with id="2"):

Given XML:
<p>
   <parent> <--- current context
       <child id="1" />
       <child id="2" />
       <child id="3" />
   </parent>
</p>

xmlNodePtr p = (parent node)// Parent node, in my example "current context"
xmlChar* attribute = (xmlChar*)"id";
xmlChar* attribute_value = (xmlChar*)"2";
xmlChar* xml_str;

for(p=p->children; p!=NULL; p=p->next){
  xml_str = xmlGetProp(p, attribute);
  if(xml_str == attribute_value){
     // Remove this node
   }
}
xmlFree(xml_str);

2 Answers 2

5

Call xmlUnlinkNode to remove a node. Call xmlFreeNode to free it afterward, if you want:

for (p = p->children; p; ) {
  // Use xmlStrEqual instead of operator== to avoid comparing literal addresses
  if (xmlStrEqual(xml_str, attribute_value)) {
    xmlNodePtr node = p;
    p = p->next;
    xmlUnlinkNode(node);
    xmlFreeNode(node);
  } else {
    p = p->next;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Haven't used this library in a while, but check out this method. Note that per the description, you need to call xmlUnlinkNode first.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.