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

时间:2012-08-13 22:43:17

标签: 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);

2 个答案:

答案 0 :(得分: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;
  }
}

答案 1 :(得分:0)

暂时没有使用过此库,但请查看this method。请注意,根据说明,您需要先调用xmlUnlinkNode