简体   繁体   English

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

[英]Xpath How remove child node by attribute c++ libxml2

How do I remove a child with a specific attribute? 如何删除具有特定属性的孩子? I´m using c++/libxml2. 我正在使用c ++ / libxml2。 My attempt so far (in the example I want to remove child node with id="2"): 到目前为止,我的尝试(在示例中,我想删除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);

Call xmlUnlinkNode to remove a node. 调用xmlUnlinkNode删除节点。 Call xmlFreeNode to free it afterward, if you want: 如果需要,请调用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;
  }
}

Haven't used this library in a while, but check out this method . 已有一段时间没有使用此库,但请查看此方法 Note that per the description, you need to call xmlUnlinkNode first. 请注意,根据描述,您需要首先调用xmlUnlinkNode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM