Using the API to insert elements
Describes useful methods to ensure schema validity when creating new elements.
Adding and inserting elements
New elements can easily be created, but if you want to insert them you can run into some problems, because the schema might not always like it.
var document = node.getOwnerDocument();
var newnode = document.createElement('newnode');
document.getDocumentElement().appendChild(newnode);
When manipulating the tree, be aware of that the above is only valid if the schema allows newnode elements at the end of the documentElement.
When however you want to insert complex structures, or insert elements into complex structures, there are several methods that make life a little easier.
//first let's insert it somewhere,
//so that the editor can understand the element according to the schema
var firstChild = document.getDocumentElement().getFirstChild();
document.getDocumentElement().insertNear(newnode, firstChild);
InsertNear tries to find a suitable location for the node within the structure of the parent. It is still better to know what you are doing though as schemas are quite precise and not forgiving.
Additionally, you could check if it is possible to add the node in the current location with canAppendChild..
Should newnode have several mandatory childnodes, they will now be created by calling makeValid, and save you a lot of work in creating and appending them in order yourself.
//now that the newnode is in the document, it can be validated
//therefore it can also be made valid:
newnode.makeValid();
One last method can be quite handy. The openAttributesEditor method opens the Attributes Editor for the specified node, in this case newnode. When the node has no attributes, nothing will happen. However, if the node does have attributes then with this method you provide your users with the dialog. This can be quite useful when you are editing lookup values, such as images. Should you constrain the src attributes of images to a lookup, then calling the above method immediately opens the lookup also, and thus saves your users two or three clicks and mouse moves.
<xsl:template match="mynode">
<div onclick="node.openAttributesEditor();">
<xsl:apply-templates/>
</div>
</xsl:template>