Search code examples
phpxmlsimplexmldomdocumentxml-namespaces

Is it OK to have a default namespace (xmlns) AND a prefixed namespace pointing to the same URI?


We're trying to generate some namespaced XML (attributes and all) but we're noticing some issues when outputting prefixes with both SimpleXML and DOMDocument in PHP. This is our test output:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:a="http://default" xmlns:b="http://extra" xmlns="http://default">
  <a:test_default>alpha</a:test_default>
  <b:test_extra>bravo</b:test_extra>
</root>

The reason I ask - we wanted to include the attributes in the namespace, but we're aware that attributes do not take the namespace of their containing element. We normally have a default namespace for our nodes. Thus, we concluded a prefix namespaced declaration would also be needed. However, when generating XML via SimpleXML or DOMDocument, prefixes are never added to the attributes.

Is there a better way? We were trying to avoid prefixing every element in the XML - utilising the default to make the content more readable.


Solution

  • Yes, it's quite OK to do this. It's often done in XSD, for example.