javascript - 如何在javascript中获取xml命名空间

标签 javascript xml namespaces

我的 xml

<message to="to_test" from="from_test">
    <test xmlns="google:mobile:data">
        {"message":"test_message"}
    </test>
</message>

我通过使用函数 getChildText("pcm") 获取值 {"message":"test_message"}。但我试图检索命名空间 xmlns 值。

我尝试了以下 How to get XML namespace? , How to get specific XML namespace in XQuery in SQL Server运气不好,它告诉我不是函数错误我做错了什么?

我忘记说了,我目前正着手使用 node.js

更新

上面的xml输出是xmpp stanza

在这里,我使用以下方法获取 attrs

stanza.attrs.to 给我 to_test

stanza.attrs.from 给我 from_test

stanza.getChildText("test") 给我 {"message":"test_message"}

我尝试使用

获取 xmlns
    var parser = new DOMParser();
    var documents = parser.parseFromString(stanza, 'text/xml');
    var response = documents.responseXML.getElementsByTagName("test");
    var sunrise = response[0].getElementsByTagNameNS("[Namespace URI]", "test")[0].getAttribute("xmlns");
    console.log(sunrise);

我来了

[xmldom error]  element parse error: TypeError: source.indexOf is not a function @#[line:0,col:undefined]

最佳答案

使用标准浏览器的 DOM 解析器,您可以执行以下操作:

var txt = "<message><test xmlns=\"google:mobile:data\"> {\"message\":\"test_message\"}</test></message>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(txt,"text/xml");
ns = xmlDoc.getElementsByTagName("test")[0].namespaceURI

我已经使用 Chrome 和 IE 进行了测试,并且可以正常工作。

关于javascript - 如何在javascript中获取xml命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35471899/

相关文章:

c++ - 为什么(或何时)模板引入其命名空间?

javascript - 输入数据后我的表格无法正确显示

javascript - 使用 AngularJs 在自定义 TinyMCE 编辑器中添加动态数据

c# - 修改xml中的属性名

c# - 在 C# 中解析 XML 以检索值

php - 具有相同命名空间的不同 Composer 包

javascript - 当父函数接收不同参数时如何实现管道

javascript - 使 extjs textarea 不可编辑

c# - GetPrintCapabilities 不会返回所有页面大小

php - 在 fatfree 框架中实现命名空间