Javascript xml 解析器:如何获取具有“:"的节点在名字里 [英] Javascript xml parser: how to get nodes that have ":" in the name

查看:30
本文介绍了Javascript xml 解析器:如何获取具有“:"的节点在名字里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码试图获取 c:CreationDate 节点:

I have the following code where i'm trying to get the c:CreationDate nodes:

 value = '<?xml version="1.0" encoding="UTF-8"?><content><c:CreationDate>2010-09-04T05:04:53Z</c:CreationDate></content>';

 xml = (new DOMParser()).parseFromString(value, 'text/xml');

 console.log(xml.getElementsByTagName('c:CreationDate'));

不幸的是,它返回一个空数组,而不是一个包含 xml 中节点的数组.我认为这是由于:"符号引起的.

Unfortunately it's returning an empty array, instead of an array with the node that is in the xml. I think that this is caused because of the ":" symbol.

有没有办法摆脱它?

注意:请不要建议在 childNodes 或类似的东西上使用.这对我不起作用,因为我的 xml 验证复杂(这里只是一个示例)并且很可能在未来发生变化,我只能依赖标签名称.

Note: Please, do not suggest usage on childNodes or things like this. This will not work for me since my xml is verify complex ( here is just a sample ) and will most likely change in the future and i can only rely in tag name.

谢谢!

推荐答案

c:CreationDate 中的 c 表示 XML 命名空间 前缀.命名空间前缀只是命名空间的快捷方式.必须使用 xmlns:c 属性在文档中的某处定义命名空间.但是在您的文档中缺少名称空间定义.

The c in c:CreationDate denotes an XML namespace prefix. The namespace prefix is only a shortcut for the namespace. The namespace has to be defined somewhere in the document with an xmlns:c attribute. But in your document the namespace definition is missing.

所以它应该是这样的:

var value = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<content>' +
            '  <c:CreationDate xmlns:c="http://my.namespace">2010-09-04T05:04:53Z</c:CreationDate>' +
            '</content>';

var value = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<content xmlns:c="http://my.namespace">' +
            '  <c:CreationDate>2010-09-04T05:04:53Z</c:CreationDate>' +
            '</content>';

在此示例中,前缀 c 被分配给命名空间 http://my.namespace.CreationDate 标记以 c 为前缀,因此它属于命名空间 http://my.namespace.

In this example the prefix c is assigned to the namespace http://my.namespace. The CreationDate tag is prefixed with c, so it belongs to the namespace http://my.namespace.

然后您可以使用命名空间感知 getElementsByTagNameNS() 函数来查询 CreationDate 元素:

Then you can use the namespace aware getElementsByTagNameNS() function to query for the CreationDate element:

console.log(xml.getElementsByTagNameNS('http://my.namespace', 'CreationDate'));

作为第一个参数,您必须传递真实的命名空间名称,而不是前缀.

As the first parameter you have to pass the real namespace name and not the prefix.

这篇关于Javascript xml 解析器:如何获取具有“:"的节点在名字里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆