You have to be really careful when you start thinking about deleting shading nodes, especially outside of very basic test environments. You can't often just delete entire connected node networks safely, because you have to make sure parts of them are not being used by other objects in the scene. How do you know the material is not being used by another object you forgot to select? Maybe the connected material is only used by the selected object, but what if it uses a texture that is also used by another material? etc. A lot of node network traversal is involved and a lot of cross-checking and it gets pretty tedious pretty quick.
Additionaly, the material node you typically see and edit is not what's directly connected to the mesh, it's attached via a shadingGroup/shadingEngine node.
Making scripts like this is all about using the listConnections and listHistory commands (multiple times) to traverse the node graph and make decisions about what you find as you go.
Here's a simple example that will simply print the material nodes found for the selected mesh objects:
{
// get the selected meshes
string $selection[] = `ls -sl -type mesh -dag`;
// first we have to find out what shadingEngine(s) are connected
string $engines[] = `listConnections -type shadingEngine $selection`;
// now we have to find what materials the engines are connected to:
string $materials[] = `listConnections -type lambert $engines`;
// we may have multiple materials, so iterate over each individually
for ($mat in $materials)
{
print("Material: "+$mat+"\n");
// listConnections is useful for the immediate connection info,
// but if we want more network nodes, we can also use listHistory
string $network[] = `listHistory $mat`;
print "nodes:\n";
print $network;
print "\n";
}
}