Java Reference
In-Depth Information
We start out by creating the StringBuffer object and appending a newline and the indent to it to make
each element start on a new line. This should result in a document we can read comfortably in a text editor.
After saving the name of the current node in nodeName , we determine what kind of node we are
dealing with in the switch statement. We could have used the instanceof operator and if
statements to do this but here there's a chance to try out the alternative approach that we discussed
earlier. We only identify two cases in the switch, corresponding to the constants Node.ELEMENT _ NODE
and Node.TEXT _ NODE . This is because our DTD for Sketcher doesn't provide for any others so we
don't expect to find them.
For a node that is an element we begin appending the start tag for the element, including the element
name. We then check for the presence of attributes for this element. If there are some, we get them as a
NamedNodeMap object in the same manner as our earlier example. We then just iterate through the
collection of attributes and build the text that corresponds to each, appending the text to the
StringBuffer object nodeStr .
Once we have finished with the attributes for the current node, we determine whether it has child nodes. If it
has no child nodes, it has no content, so we can complete the tag for the current node making it an empty
element. Since the element is now complete we can return it as a String . If the current element has child
nodes we obtain those in a NodeList object. We then iterate through the nodes in the NodeList and call
getDocumentNode() for each with an extra space appended to indent . The String that is returned for
each call is appended to nodeStr . When all the child nodes have been processed we are done so we can
exit the switch and return the contents of nodeStr as a String .
The other possibility is that the current node is text. This will arise from an Element.Text object in
the sketch. It is also possible that this text may contain double quotes - the delimiter that we are using
for strings in our XML. We therefore call replaceQuotes() to replace all occurrence of QUOTE in
the text with the QUOTE _ ENTITY constant that we defined in our Constants interface, before
appending the string to nodeStr .
We can implement the replaceQuotes() method in SketchFrame as:
public String replaceQuotes(String str) {
StringBuffer buf = new StringBuffer();
for(int i = 0 ; i<str.length() ; i++)
if(str.charAt(i)==QUOTE)
buf.append(QUOTE _ ENTITY);
else
buf.append(str.charAt(i));
return buf.toString();
}
This just tests each character in the original string. If it's a delimiter for an attribute value, it's replaced
by the entity reference &quot; in the output string buf .
Well, we are done - almost. We must not forget the extra import statements we need in the
SketchFrame.java file:
Search WWH ::




Custom Search