I am creating several XML files via Java and up to this point everything worked fine, but now I\'ve run into a problem when trying to create a file with namespace prefixed n
Wrong method, try the *NS variants:
Element mainRootElement = doc.createElementNS(
"http://abc.de/x/y/z", // namespace
"tns:cmds" // node name including prefix
);
First argument is the namespace, second the node name including the prefix/alias. Namespace definitions will be added automatically for the namespace if needed. It works to set them as attributes, too.
The namespace in your original source is http://abc.de/x/y/z
. With the attribute xmlns:tns="http://abc.de/x/y/z"
the alias/prefix tns
is defined for the namespace. The DOM api will implicitly add namespaces for nodes created with the *NS methods.
xmlns
and xml
are reserved/default namespace prefixes for specific namespaces. The namespace for xmlns
(namespace definitions) is http://www.w3.org/2000/xmlns/
.
To add an xmlns:* attribute with setAttributeNS() use the xmlns namespace:
mainRootElement.setAttributeNS(
"http://www.w3.org/2000/xmlns/", // namespace
"xmlns:xsi", // node name including prefix
"http://www.w3.org/2001/XMLSchema-instance" // value
);
But even that is not needed. Just like for elements, the namespace definition will be added implicitly if you add an attribute node using it.
mainRootElement.setAttributeNS(
"http://www.w3.org/2001/XMLSchema-instance", // namespace
"xsi:schemaLocation", // node name including prefix
"http://abc.de/x/y/z xyzschema.xsd" // value
);
If you see a nodename like xsi:schemaLocation
you can resolve by looking for the xmlns:xsi
attribute. This attribute is the namepace definition. The value is the actual namespace. So if you have an attribute xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
the node name can be resolved to {http://www.w3.org/2001/XMLSchema-instance}schemaLocation
(Clark notation).
If you want to create the node you need 3 values:
http://www.w3.org/2001/XMLSchema-instance
schemaLocation
xsi
The prefix is optional for element nodes, but mandatory for attribute nodes. The following three XMLs resolve all to the element node name {http://abc.de/x/y/z}cmds
:
<tns:cmds xmlns:tns="http://abc.de/x/y/z"/>
<cmds xmlns="http://abc.de/x/y/z"/>
<other:cmds xmlns:other="http://abc.de/x/y/z"/>