7.1.4.1 Example

If we wish to add a new “shape” to our product information, we might do it like this:

Node productsNode = root.getNode("products");

Node triangleNode = productsNode.addNode("triangle");

Node contentNode = triangleNode.addNode("jcr:content");

contentNode.setProperty("myapp:title", "Triangle: an
economical choice");

contentNode.setProperty("myapp:price", 50);

contentNode.setProperty("myapp:lead", "Triangles have

three sides, but they're not always

equal!");

productsNode.save();


This would add the new node triangle below the products node and add to triangle's jcr:content node the properties myapp:title, myapp:price and myapp:lead with the specified values.

As another example, suppose we wish to iterate through a collection of strings and add each as a new paragraph under the node triangle/jcr:content. In that case, we might do the following:

Node contentNode = triangleNode.getNode("jcr:content");

for (Iterator i = strings.iterator(); i.hasNext();) {

String text = (String) i.next();

Node paraNode = contentNode.addNode("paragraph"); paraNode.setProperty("text", text);

}


For each string retrieved from strings a new node is created called paragraph which is given a new property called text, which, in turn, is assigned the retrieved string.