Creating namespace prefixed XML nodes in Java DOM

后端 未结 1 1775
执念已碎
执念已碎 2021-01-13 16:41

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

相关标签:
1条回答
  • 2021-01-13 17:23

    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
    );
    

    Namespaces Prefixes

    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:

    1. the namespace: http://www.w3.org/2001/XMLSchema-instance
    2. the local node name: schemaLocation
    3. the prefix: 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"/>
    0 讨论(0)
提交回复
热议问题