使用javascript中的xPath使用默认命名空间解析XML [英] Parsing XML with default namespace using xPath in javascript

查看:84
本文介绍了使用javascript中的xPath使用默认命名空间解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个XML xPath解析器。所有解析都必须在客户端进行(使用javascript)。我创建了一个执行此操作的javascript,在默认命名空间发挥作用之前,所有内容都可以正常运行。我根本无法查询具有默认命名空间的XML。

I need to create an XML xPath parser. All parsing has to happen on client side (using javascript). I created an javascript that does this, and everything looks OK until default namespaces come into play. I simply can't query XML that has default namespace.

我在小提琴上创建了一个示例代码。在xmlString中是从服务器接收的XML字符串。在xPathString中是对收到的XML进行查询。

I created an example code on fiddle. In xmlString is XML string received from server. In xPathString is query done on received XML.

以下是一些场景:


  1. http://jsfiddle.net/BF34q/1/ - 没有名称空间 - 一切正常

  2. http://jsfiddle.net/BF34q/2/ - 添加了ns名称空间element有ns:前缀。 xPath使用此前缀 - 确定

  3. http://jsfiddle.net/BF34q / 3 / - 使用默认命名空间 - 不确定如何配置xPathString。

  1. http://jsfiddle.net/BF34q/1/ - no namespaces - everything works OK
  2. http://jsfiddle.net/BF34q/2/ - ns namespace added. element has ns: prefix. xPath uses this prefix - OK
  3. http://jsfiddle.net/BF34q/3/ - default namespace used - not sure how to configure xPathString.

注意其他人将使用此解析器,所以我真的想避免像这样的解决方案

Note that others will use this parser, so I would really like to avoid solutions like

var xPathString = "//*[local-name()='book']";

并使他们能够使用简单的xPath表达式解析它。我想知道是否可以在javascript中指定默认名称空间前缀?

and enable them to parse it using simple xPath expressions. I wonder if it is possible to assign default namespace prefix in javascript?

注意:小提琴上提供的示例在IE中不起作用。

Note: The example provided on fiddle will not work in IE.

推荐答案

我认为有三种方法可以做到这一点:

I think there are three ways to do this:


  1. 使用 // * [local-name()='book'] 访问节点的语法

  2. 将XML转换为字符串,使用RegExp删除默认命名空间,将其转换回XML

  3. 对于事先知道命名空间的XML文件,您可以创建自己的命名空间解析器,它允许您使用自己的前缀作为默认命名空间。

  1. Use //*[local-name()='book'] syntax for accessing nodes
  2. Convert XML to string, remove default namespace using RegExp, convert it back to XML
  3. For XML files where you know namespaces in advance, you can create your own namespace resolver, which will allow you to use your own prefix for default namespace.

这可以这样实现:

function nsResolver(prefix) {
    switch (prefix) {
        case 'xhtml':
            return 'http://www.w3.org/1999/xhtml';
        case 'mathml':
            return 'http://www.w3.org/1998/Math/MathML';
        default:
            return 'http://example.com/domain';
    }
}
xml.evaluate('//myPrefix:book', xml, nsResolver, XPathResult.ANY_TYPE, null);

这篇关于使用javascript中的xPath使用默认命名空间解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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