Susan said:
I was hoping that some guru that is familiar with java DOM APIs might be
able to tell me:
I don't know that I qualify for guru status, but I will attempt to
address your questions inline below.
1. Is the preferred way to do it?
2. Is something wrong with this approach?
3. Is there a better approach?
I think this is a pretty good way to do it, to here. In particular, in
order to get a Document with a namespace URI (or DocumentType) via the
standard interfaces, you need to go through a DOMImplementation, as you
show. Also, setting the namespace prefix as you show is fine, though as
I read the docs, it would be equally OK to just feed the qualified name
to the DOMImplementation in the first place. (I'd test.)
Testing shows that this is not generated for you, but that does not
necessarily mean that you need to generate it yourself -- it depends on
how you plan to use the Document. Remember that Within DOM (and XML in
general) the namespace prefix is secondary in importance to the
namespace URI. Multiple prefixes that map to the same namespace URI are
equivalent, so that <foo:element xmlns:foo="urn:foobar"/> is
Well, yes and no. Namespace _declarations_ seem to be at a higher
semantic level than DOM, though they are implied by elements' and
attributes' prefixes and namespace URIs. If you don't intend to naively
(or at all) process your Document to produce XML text then the namespace
declarations don't much matter.
If you do want to produce XML text, then a processor can conceivably
track elements' and attributes' prefixes and assigned namespace URIs in
order to insert namespace declarations in a manner that produces a
compliant document. Ideally, such a processor would recognize literal
namespace declarations, too, though it wouldn't need to do.
Alternatively, you can insert the correct declarations in the correct
places, which might make life easier, but which might not do a good job
of accommodating things like an Element of one Document being adopt()ed
into a different one, or an Element being moved around within one Document.
I don't quite see the connection. The SAX2 events deliver the
information necessary to assign the correct namespace URI to each
element and attribute in the XML stream. With DOM, on the other hand,
the namespace URIs are carried inherently by Element and Attr Nodes. I
reiterate: it is these URI that are of principal importance, not the
namespace prefixes. It is anyway the case that if a compliant document
is parsed into DOM then it should contain namespace declarations in the
correct places, despite the fact that these are not used internally to
associate elements and attributes with their namespaces.
I'm not sure I agree, but do note in any case that DOM is not
Java-specific, but rather a W3C project. The Java binding for DOM is
provided by the W3C as well, I believe -- observe the name of the
relevant package (org.w3c.dom). SAX is also an external specification,
for what it's worth.