如何删除具有特定属性的子项?我使用的是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);
答案 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
。