如何使用 Javascript 删除 XML 命名空间? [英] How to remove XML namespaces using Javascript?

查看:35
本文介绍了如何使用 Javascript 删除 XML 命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,就我的目的而言,XML 命名空间只是引起了很多头痛,完全没有必要.(例如,它们如何使 xpath 复杂化.)

I am finding that, for my purposes, XML namespaces are simply causing much headache and are completely unnecessary. (For example, how they complicate xpath.)

是否有一种简单的方法可以从 XML 文档中完全删除命名空间?

Is there a simple way to remove namespaces entirely from an XML document?

(有一个相关的问题,但它涉及删除标签上的命名空间前缀,而不是从文档根目录中删除命名空间声明:使用 javascript 删除 XML 命名空间的简单方法".)

(There is a related question, but it deals with removing namespace prefixes on tags, rather than namespace declarations from the document root: "Easy way to drop XML namespaces with javascript".)

示例和更多详细信息如下:

Samples and more detail below:

XML:

<?xml version="1.0" ?>
<main xmlns="example.com">
  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>
</main>

JavaScript:

function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}

示例 XML 就像我正在使用的实际 XML,但要短得多.请注意,名称空间的标记上没有 前缀.我假设这是 null 或默认命名空间.

The sample XML is just like the actual one I am working with, albeit much shorter. Notice that there are no prefixes on the tags for the namespace. I assume this is the null or default namespace.

JavaScript 是我的 ajax 函数的一个片段.如果我从 main 标记中删除 xmlns="example.com" 部分,我就能够成功获取该值.只要存在任何命名空间,该值就会变为未定义.

The JavaScript is a snippet from my ajax functions. If I remove the xmlns="example.com" portion from the main tag, I am able to successfully get the value. As long as any namespace is present, the value becomes undefined.

编辑 2:

值得一提的是,在 XML 标记中实际上没有使用任何声明的命名空间(如上面的示例).在我使用的实际 XML 文件中,声明了三个命名空间,但没有以命名空间引用为前缀的标记.因此,也许问题应该重新命名为如何使用 Javascript 删除未使用的 XML 名称空间?"如果命名空间是 1) 从未使用过和 2) 使用 xpath 使节点的简单路径复杂化,我看不出保留命名空间的理由.

It may be worth mentioning that none of the declared namespaces are actually used in the XML tags (like the sample above). In the actual XML file I am working with, three namespaces are declared, but no tags are prefixed with a namespace reference. Thus, perhaps the question should be re-titled, "How to remove unused XML namespaces using Javascript?" I do not see the reason to retain a namespace if it is 1) never used and 2) complicating an otherwise simple path to a node using xpath.

推荐答案

这应该删除您找到的所有命名空间声明:

This should remove any namespace declaration you find:

var xml = http.responseXML.replace(/<([a-zA-Z0-9 ]+)(?:xml)ns=\".*\"(.*)>/g, "<$1$2>");

这篇关于如何使用 Javascript 删除 XML 命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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