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

标签 javascript xml node.js xml-namespaces xmldom

如何将带有 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/

相关文章:

java - TextView 中从右到左的文本

javascript - 我如何将 .not jquery 与 .serialize 一起使用

javascript - 通过 Axios 发送 post 请求会在 Spring-Boot 后端生成一个空的 RequestBody。在 Postman 中工作,但不能通过 Axios 发布请求

java - spring 外部属性文件;文件未找到异常

node.js - 了解node Angular Express和mongo之间的通信

javascript - Upsert 性能随着集合(文档数量)的增加而降低

node.js - stripe connect 创建客户的正确电话号码格式

javascript - 如何获取 HTML 文档动态修改的 SVG 元素的字符串?

javascript - 显示用户角色 : angularjs, rolify,rails 应用程序

mysql - 在 MySQL 中解析 XML 字符串