Xpath如何通过属性c ++ libxml2删除子节点

use*_*032 2 c++ xpath libxml2

如何删除具有特定属性的子项?我使用的是c ++/libxml2.到目前为止我的尝试(在示例中我想删除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);
Run Code Online (Sandbox Code Playgroud)

Rob*_*edy 5

调用xmlUnlinkNode删除节点.xmlFreeNode如果您愿意,请随后致电以释放它:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)