Element Node Validation
The ElementEditVAL interface provides methods for dynamically validating an element node. Some of the commonly used methods of ElementEditVAL interface are discussed in Table 1. I've provided a more detailed description and examples of these methods in the following sections of this article.
Table 1. ElementEditVAL Methods: The table shows common ElementEditVal methods you'll use when dynamically validating elements in an XML document.
| Method |
Usage |
| canAppendChild() |
Determine whether appending a child element would be valid. |
| canRemoveChild() |
Determine whether removing a child element would be valid. |
| getAllowedChildren() |
Obtain the sub elements that may be added to an element. |
| getContentType() |
Obtain the content type of an element; empty, text only, elements, or mixed. |
| getAllowedAttributes() |
Obtain the attributes that may be added to an element. |
| getRequiredAttributes() |
Obtain the required attributes of an element. |
| canSetAttribute() |
Determine if an attribute may be set. |
| canRemoveAttribute() |
Determine if an attribute may be removed. |
The canAppendChild() Method
You can test the validity of appending an element using the
canAppendChild() method.
As an example, suppose you want to append a
journal element to the
catalog element in the sample document. You first get a reference to the
catalog element, create the journal element, and then use the
canAppendChild() method to check whether appending it to the catalog element would be a valid operation, as shown below:
XMLElement catalogElement = (XMLElement)
(document.getDocumentElement());
ElementEditVAL elementEditVAL = (ElementEditVAL)
(catalogElement);
Element journalElement =
document.createElement("journal");
short editValJournal =
elementEditVAL.canAppendChild(journalElement);
In this case, because the journal element is defined in the catalog element (see
Listing 2), the output in the example validation program is:
Element Addition is VALID_TRUE
The canRemoveChild() Method
The
canRemoveChild() method checks the validity of removing an element. As an example, if you check to see if you can remove the
journal element, you'll get a
VALID_TRUE return value, because the schema specifies it as
minOccurs=0.
XMLElement journal = (XMLElement)
(catalogElement.getElementsByTagName(
"journal").item(0));
short elementRemove = documentEditVAL.canRemoveChild(
journal);
The
isElementDefined() method checks whether a global element is defined in a schema. For example, to check whether a
title element is defined in the sample schema, you can write:
short elementDefined =
elementEditVAL.isElementDefined("title");
Because the
title element defined in the
catalog.xsd schema is not a global element the return value is
VALID_FALSE.