Hello,

I am trying to write some code that will walk through an XML document
and remove any nodes (and their children) with a particular name.
Unfortunately my code is not working as I expected.

I have attached a small example C program and XML document.  My
expectation is that the program would remove the three <extensions>
nodes and their children, in reality the program fails to remove the
<extensions> child of the <sub2> node.

To fix the problem I have tried swapping the order of the if statement
and the recursive call to strip_extensions in the for loop, but with no
effect.

I am probably overlooking something really simple, could some one point
it out for me :-)

Thanks,

Keith.
/* test.c
 *
 * Test program to strip all <extensions> nodes from a file
 *
 * To compile:
 *	gcc -o test test.c `pkg-config --cflags --libs libxml-2.0`
 */

#include <libxml/tree.h>

void
strip_extensions (xmlNode *node)
{
	xmlNode *cur_node = NULL;

	for (cur_node = node; cur_node; cur_node = cur_node->next) {
		if (strcmp (cur_node->name, "extensions") == 0) {
			fprintf (stderr, "Node: %s\n", cur_node->parent->name);
			xmlUnlinkNode (cur_node);
			xmlFreeNode (cur_node);
		}
		strip_extensions (cur_node->children);
	}
	return;
}

int
main (int argc, char *argv[])
{
	int size;
	xmlChar *buf;
	xmlDoc *doc;
	xmlNode *root;
	
	doc = xmlReadFile (argv[1], NULL, 0);
	root = xmlDocGetRootElement (doc);

	strip_extensions (root);

	xmlDocDumpMemory (doc, &buf, &size);
	
	fprintf (stdout, "%s", buf);
	
	xmlFree (buf);
	xmlFreeDoc (doc);
	xmlCleanupParser ();	

	return 0;
}

Attachment: test.xml
Description: application/xml

_______________________________________________
xml mailing list, project page  http://xmlsoft.org/
[email protected]
http://mail.gnome.org/mailman/listinfo/xml

Reply via email to