Java Reference
In-Depth Information
// Set angle field value from a node
protected void setAngleFromXML(Node node) {
angle =
Double.valueOf(((Attr)(node.getAttributes().getNamedItem("angle"))).getValue());
}
Directory "Sketcher reading and writing XML"
The
Node
object that is passed to the method contains the value for
angle
as an attribute. Calling
getAt-
tributes()
for
node
returns all the attributes as a
NamedNodeMap
object. Calling
getNamedItem()
for this
object returns the attribute, with the name you pass as the argument, as a
Node
object. The
getValue()
method for a
Node
object returns its value as a
String
object, so passing this to the static
valueOf()
method
in the
Double
class returns the
angle
value as type
double
.
This pattern for obtaining the value of an attribute from a
Node
object appears frequently. Here's how you
can initialize the
position
field with another method in the
Element
class:
// Set position field from a node
protected void setPositionFromXML(Node node) {
NamedNodeMap attrs = node.getAttributes();
position = new Point(
Integer.valueOf(((Attr)(attrs.getNamedItem("x"))).getValue()),
Integer.valueOf(((Attr)(attrs.getNamedItem("y"))).getValue()));
}
Directory "Sketcher reading and writing XML"
This method closely parallels the previous method. You extract the values for the coordinates of the point
from the attributes as integers. You then pass these to a
Point
class constructor.
The code to initialize the
color
field is very similar:
// Set color field from a node
protected void setColorFromXML(Node node) {
NamedNodeMap attrs = node.getAttributes();
color = new Color(
Integer.valueOf(((Attr)(attrs.getNamedItem("R"))).getValue()),
Integer.valueOf(((Attr)(attrs.getNamedItem("G"))).getValue()),
Integer.valueOf(((Attr)(attrs.getNamedItem("B"))).getValue()));
}
Directory "Sketcher reading and writing XML"