Repository navigation
Open
Description
Describe the bug
When parsing, a default namespace declaration on a prefixed element is applied to the element itself. A default namespace never applies to prefixed names (Namespaces in XML §6.2). This causes three problems:
<p:a xmlns:p="urn:u" xmlns="urn:v">gets namespaceurn:v. With the attributes in the other order it getsurn:u, so the result depends on attribute order, and prefixed children inherit the wrong namespace.<p:a xmlns:p="urn:u" xmlns=""/>throws a NamespaceError.- A prefixed attribute loses its namespace when that namespace equals the default namespace.
To Reproduce
const { create } = require('xmlbuilder2');
const show = s => {
try {
const d = create(s);
const e = d.root().node;
console.log(
s, '=>', e.namespaceURI,
[...e.childNodes].map(c => c.nodeName + '=' + c.namespaceURI),
[...e.attributes].filter(a => !a.name.startsWith('xmlns')).map(a => a.name + '=' + a.namespaceURI),
d.end({ headless: true })
);
} catch (err) {
console.log(s, 'THROW', err.message);
}
};
show('<p:a xmlns="urn:v" xmlns:p="urn:u"/>'); // control
show('<p:a xmlns:p="urn:u" xmlns="urn:v"><p:b/><c/></p:a>'); // 1
show('<p:a xmlns:p="urn:u" xmlns=""/>'); // 2
show('<a xmlns="urn:u" xmlns:p="urn:u" p:x="1"/>'); // 3Output:
<p:a xmlns="urn:v" xmlns:p="urn:u"/> => urn:u [] [] <p:a xmlns="urn:v" xmlns:p="urn:u"/>
<p:a xmlns:p="urn:u" xmlns="urn:v"><p:b/><c/></p:a> => urn:v [ 'p:b=urn:v', 'c=urn:v' ] [] <ns1:a xmlns:ns1="urn:v" xmlns:p="urn:u" xmlns="urn:v"><b/><c/></ns1:a>
<p:a xmlns:p="urn:u" xmlns=""/> THROW The operation is not allowed by Namespaces in XML. [XMLNS] Qualified name includes a prefix but the namespace is null.
<a xmlns="urn:u" xmlns:p="urn:u" p:x="1"/> => urn:u [] [ 'p:x=null' ] <a xmlns="urn:u" xmlns:p="urn:u" p:x="1"/>
Expected behavior
p:aandp:bare inurn:u,cis inurn:v, and serializing gives back<p:a xmlns:p="urn:u" xmlns="urn:v"><p:b/><c/></p:a>.- No error;
p:ais inurn:u. p:xis inurn:u.
Version:
- node.js: 26.13.0
- xmlbuilder2: 4.0.3 (also master at 10b6549)
Additional context
In src/readers/XMLReader.ts, if (attName === "xmlns") { namespace = attValue } runs even when the element has a prefix, and attribute resolution clears the namespace whenever isDefaultNamespace(attNamespace) is true, also for prefixed attributes.
Credit: https://ucsbplse.github.io/
Metadata
Metadata
Assignees
Labels
No labels
Activity