Java Reference
In-Depth Information
Attr attr = doc.createAttribute("x");
attr.setValue(String.valueOf(bounds.x));
boundsElement.setAttributeNode(attr);
attr = doc.createAttribute("y");
attr.setValue(String.valueOf(bounds.y));
boundsElement.setAttributeNode(attr);
attr = doc.createAttribute("width");
attr.setValue(String.valueOf(bounds.width));
boundsElement.setAttributeNode(attr);
attr = doc.createAttribute("height");
attr.setValue(String.valueOf(bounds.height));
boundsElement.setAttributeNode(attr);
return boundsElement;
}
Directory "Sketcher reading and writing XML"
This method extracts the
x
and
y
coordinates of the top-left corner and the values of the
width
and
height
for the
bounds
member of the Sketcher
Element
class and sets these as attribute values for the
<bounds>
XML element.
Adding a Line Node
The method to add a
<line>
node to the
Document
object creates an XML
<line>
element with an
angle
attribute and then adds four child elements:
<color>
,
<position>
,
<endpoint>
, and
<bounds>
. You can
add the following implementation of the
addElementNode()
method to the
Element.Line
class:
// Create XML element for a line
public void addElementNode(Document doc) {
org.w3c.dom.Element lineElement = doc.createElement("line");
// Create the angle attribute and attach it to the <line> node
Attr attr = doc.createAttribute("angle");
attr.setValue(String.valueOf(angle));
lineElement.setAttributeNode(attr);
// Append the <color>, <position>, and <endpoint> nodes as children
lineElement.appendChild(createColorElement(doc));
lineElement.appendChild(createPositionElement(doc));
lineElement.appendChild(createBoundsElement(doc));
lineElement.appendChild(createEndpointElement(doc));
// Append the <line> node to the document root node
doc.getDocumentElement().appendChild(lineElement);
}