I have simple code where I create root element and append child to it. The problem is that child appends with empty xmlns=""
attribute, though I don't expect it. It is a problem only of the first child, and the child of second nesting level is already Ok.
So, the following code -
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element rootEl = doc.createElementNS("http://someNamespace.ru", "metamodel");
doc.appendChild(rootEl);
Element groupsEl = doc.createElement("groups");
// This appends with xmlns=""
rootEl.appendChild(groupsEl);
Element groupEl = doc.createElement("group");
// This appends normally
groupsEl.appendChild(groupEl);
Will result to output -
<?xml version="1.0" encoding="UTF-8"?>
<metamodel xmlns="http://someNamespace.ru">
<groups xmlns="">
<group/>
</groups>
</metamodel>
Instead of -
<?xml version="1.0" encoding="UTF-8"?>
<metamodel xmlns="http://someNamespace.ru">
<groups>
<group/>
</groups>
</metamodel>
Note, as I said above, the tag <group>
is already free from xmlns
.
You declare default namespace (namespace without prefix) for parent and by default all children should belong to the same namespace. If they don't, xmlns="" is generated to show that they don't belong to parent's namespace.
xml file, add a namespace declaration to the root sites element, associating the xs prefix with the URI for the XML Schema namespace. Specify the default namespace http://example.com/weekendfunsnacks/sites for the file. Specify sites. xsd as the location of the schema for the default namespace.
XML Namespaces - The xmlns Attribute When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
The xmlns attribute specifies the xml namespace for a document. Note: The xmlns attribute is required in XHTML, invalid in HTML 4.01, and optional in HTML5. Note: The HTML validator at http://w3.org does not complain when the xmlns attribute is missing in an XHTML document.
Your desired markup shows all elements in the default namespace. In order to achieve this, you have to create all elements in the default namespace.
The actual output you're getting has <groups xmlns="">
because groups
, and its group
child element were created in no namespace:
Element groupsEl = doc.createElement("groups");
Change this to
Element groupsEl = doc.createElementNS("http://someNamespace.ru", "groups");
Similarly, change
Element groupEl = doc.createElement("group");
to
Element groupEl = doc.createElementNS("http://someNamespace.ru","group");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With