Java Reference
In-Depth Information
import org.w3c.dom.Document;
import org.w3c.dom.Attr;
Note that we definitely don't want to use the * notation to import all of the names from this package. If we do,
we will get our sketcher Element class confused with the Element interface in the org.w3c.dom package.
We are going to have to use qualified names wherever there is a potential clash.
The XML elements that we will create for geometric elements in a sketch will all need <position>
and <color> elements as children. If we define methods in the base class Element , to create these,
they will be inherited in each of the subclasses of Element Here's how we can define a method in the
Element class to create a <color> element:
protected org.w3c.dom.Element createColorElement(Document doc) {
org.w3c.dom.Element colorElement = doc.createElement("color");
Attr attr = doc.createAttribute("R");
attr.setValue(String.valueOf(color.getRed()));
colorElement.setAttributeNode(attr);
attr = doc.createAttribute("G");
attr.setValue(String.valueOf(color.getGreen()));
colorElement.setAttributeNode(attr);
attr = doc.createAttribute("B");
attr.setValue(String.valueOf(color.getBlue()));
colorElement.setAttributeNode(attr);
return colorElement;
}
The method for creating the node for a position element will use essentially the same process, but we
have several nodes that represent points that are the same apart from their names. We can share the
code by putting it into a method that we call with the appropriate type name:
protected org.w3c.dom.Element createPointTypeElement(Document doc,
String name,
String xValue,
String yValue) {
org.w3c.dom.Element element = doc.createElement(name);
Attr attr = doc.createAttribute("x"); // Create attribute x
attr.setValue(xValue); // and set its value
element.setAttributeNode(attr); // Insert the x attribute
attr = doc.createAttribute("y"); // Create attribute y
attr.setValue(yValue); // and set its value
element.setAttributeNode(attr); // Insert the y attribute
return element;
}
This will create an element with the name specified by the second argument so we can use this in a
method in the Element class to create a node for a <position> element:
Search WWH ::




Custom Search