gpt4 book ai didi

javascript - 添加合格的 XML 元素不会继承命名空间 URI

转载 作者:太空宇宙 更新时间:2023-11-03 22:37:35 25 4
gpt4 key购买 nike

如何将带有 ns 前缀的元素附加到另一个元素并使其继承文档中的命名空间URI 映射?

举个例子:实例化一个解析 XML 字符串的文档:pp:q 元素从 root 继承 namespaceURI == 'abc'元素,但将新元素 pp:q 附加到 root,新元素具有 namespaceURI == null

doc = new DOMParser().parseFromString(
'<root xmlns:pp="abc">'
+'<pp:q/>'
+'<q/>'
+'</root>'
,'text/xml');
root = doc.firstChild;

x = root.getElementsByTagName("pp:q").item(0);
console.log(x.namespaceURI); // logs abc

y = doc.createElement('pp:q')
root.appendChild(y)
console.log(y.namespaceURI); //logs null

此示例使用 xmldomnodejs 中运行 library

[编辑如下以回应 kjhughes]

我也尝试过createElementNS,但我觉得这种方式也有问题..
将这些行附加到代码中:

a = doc.createElementNS('abc', 'pp:q');
root.appendChild(a)
console.log(a.namespaceURI); //abc --- i may say it works,
//even though i'm required using
//both prefix *and* namespaceURI manually
//while for the parsed element (x)
//a lookup has been succesfully issued
// but ...

a1 = doc.createElementNS('abc', 'xx:q');
root.appendChild(a1)
console.log(a1.namespaceURI); //abc --- but prefix is xx! not according to xmlns declaration!

b = doc.createElementNS('xyz', 'VV:q');
root.appendChild(b)
console.log(b.namespaceURI); //xyz --- I can write anything!

console.log(String(doc)); //<root xmlns:pp="abc"><pp:q/><q/><pp:q/><xx:q/><VV:q/></root>

最佳答案

根据 document.createElement() 的文档,

var element = document.createElement(tagName);

element is the created element object.

tagName is a string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don't use qualified names (like "html:a") with this method.

您应该使用 document.createElementNS() .

每个问题更新更新:

请注意,命名空间本身才是重要的,而不是命名空间前缀。当您为给定命名空间提供多个前缀时,API 没有义务使用特定的命名空间前缀。此外,请意识到 .namespaceURI命名空间不是命名空间前缀

关于javascript - 添加合格的 XML 元素不会继承命名空间 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23653414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com