Setting namespaces and prefixes in a Java DOM document

不打扰是莪最后的温柔 提交于 2019-11-28 09:16:18
jtahlborn

You haven't added the namespace declaration in the root node; you just declared the root node in the namespace, two entirely different things. When building a DOM, you need to reference the namespace on every relevant Node. In other words, when you add your attribute, you need to define its namespace (e.g., setAttributeNS).

Side note: Although XML namespaces look like URLs, they really aren't. There's no need to use the URL class here.

The correct way to set a node on a namespaceAware document is by using:

rootNode.createElementNS("http://example/namespace", "PREFIX:aNodeName");

So you can replace "PREFIX" with your own custom prefix and replace "aNodeName" with the name of your node. To avoid having each node having its own namespace declaration you can define the namespaces as attributes on your root node like so:

rootNode.setAttribute("xmlns:PREFIX", "http://example/namespace");

Please be sure to set:

documentBuilderFactory.setNamespaceAware(true)

Otherwise you don't have namespaceAwareness.

Please note that setting an xmlns-prefix with setAttribute is wrong. If you ever want to eg sign your DOM, you have to use setAttributeNS: element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:PREFIX", "http://example/namespace");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!