Java Reference
In-Depth Information
The
Element
interface also declares four methods for adding attributes:
setAttributeNode(
Attr attr)
Adds the node
attr
to the element. If an attribute node with
the same name already exists, it will be replaced by
attr
.
The method returns either a reference to an existing
Attr
node that has been replaced or
null
. The method can throw
a
DOMException
with the following codes:
WRONG
_
DOCUMENT
_
ERR
if
attr
belongs to another
document,
NO
_
MODIFICATION
_
ALLOWED
_
ERR
if the element is read-
only,
INUSE
_
ATTRIBUTE
_
ERR
if
attr
already belongs to another
element.
setAttributeNodeNS(
Attr attr)
As above but applies to an element defined within a
namespace.
setAttribute(
String name,
Add a new attribute node with the specified
name
and
value
. If the attribute has already been added, its value is
changed to
value
. The method can throw
DOMException
with the codes:
String value)
INVALID
_
CHARACTER
_
ERR
if
name
contains an illegal
character,
NO
_
MODIFICATION
_
ALLOWED
_
ERR
if the element is read-
only.
setAttributeNS(
As above but with the attribute within the namespace
nsURI
.
In addition this method can throw a
DOMException
with the
code
NAMESPACE
_
ERR
if
qualifiedName
is invalid or not
within the namespace.
String nsURI,
String qualifiedName,
String value)
Since we know enough about constructing a
Document
object to have a stab at putting together an
object encapsulating a real XML document, let's have a stab at it.
Storing a Sketch as XML
We have already defined a DTD in the previous chapter that is suitable for defining a sketch. We can
see how we can put together the code to store a sketch as an XML document instead of as a serialized
object. Obviously we'll use the DTD we already have, and we can create a
Document
object with a
DocumentType
node via a
DOMImplementation
object from a
DocumentBuilder
object. We can
do this with two statements in a
try
block:
Document doc = null;
try {
DOMImplementation domImpl = DocumentBuilderFactory.newInstance()