2

如何删除具有特定属性的孩子?我正在使用 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);
4

2 回答 2

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;
  }
}
于 2012-08-13T23:11:26.827 回答
0

好久没用这个库了,看看这个方法。请注意,根据描述,您需要先致电xmlUnlinkNode

于 2012-08-13T23:06:00.337 回答