How to delete node using java code | Community
Skip to main content
New Participant
October 1, 2021
Solved

How to delete node using java code

  • October 1, 2021
  • 3 replies
  • 2823 views

I have 2-3 component node which are not required. I am writing workflow to check those node. How should I delete the node using Java.

 

Eg: 

Node1- Example

Node2- Test

 

If I find the resource.getName() as Node1 delete that node 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by manpreetk908

Hi Ronnie,

 

You can use the delete method https://sling.apache.org/apidocs/sling7/org/apache/sling/api/resource/ResourceResolver.html#delete-org.apache.sling.api.resource.Resource-

 

Alternatively, you can use - https://docs.adobe.com/content/docs/en/spec/jcr/1.0/7.1.6_Removing_Nodes_and_Properties.html

javax.jcr.Node jcrNode = jcrsession.getNode("/sites/mySite");
jcrNode.remove();
jcrsession.save();

 

Regards,

Manpreet

3 replies

Sanjay_Bangar
New Participant
October 1, 2021

Hi @ronnie09 ,

         You need to used Node api for adding and removing .

Using Node API

Adapt the resource to Node

Node node = resource.adaptTo(Node.class);

Then remove a node using function removenode(java.lang.String relPath, java.lang.String primaryNodeTypeName)"

  • node.remove(nodeName, NodePrimaryType);
  • you can add properties using function "setProperty(java.lang.String name,Value value)"
  • Save the session so that the new Node and its properties are saved

Kr,

Sanjay

manpreetk908
manpreetk908Accepted solution
New Participant
October 1, 2021

Hi Ronnie,

 

You can use the delete method https://sling.apache.org/apidocs/sling7/org/apache/sling/api/resource/ResourceResolver.html#delete-org.apache.sling.api.resource.Resource-

 

Alternatively, you can use - https://docs.adobe.com/content/docs/en/spec/jcr/1.0/7.1.6_Removing_Nodes_and_Properties.html

javax.jcr.Node jcrNode = jcrsession.getNode("/sites/mySite");
jcrNode.remove();
jcrsession.save();

 

Regards,

Manpreet

Siva_Sogalapalli
New Participant
October 1, 2021

Hi Ronnie,

 

Please check below link which has examples of deleting nodes, hope this will help you.

 

https://www.tabnine.com/code/java/methods/org.apache.sling.api.resource.ResourceResolver/delete