当给出xmlns时,DOM XPath查询不起作用 [英] DOM XPath query doesn't work when a xmlns is given

查看:82
本文介绍了当给出xmlns时,DOM XPath查询不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Firefox JavaScript控制台中:

In Firefox JavaScript console:

parser = new DOMParser();

foo = parser.parseFromString('<foo></foo>', "text/xml");
res = foo.evaluate("/foo", foo, null, 0, null);
res.iterateNext();
> [object Element]

foo = parser.parseFromString('<foo xmlns="http://foo.bar.baz/quux"></foo>', "text/xml");
res = foo.evaluate("/foo", foo, null, 0, null);
res.iterateNext();
> null

res = foo.evaluate("*[1]", foo, null, 0, null);
res.iterateNext();
> [object Element]

如果XML文档不包含xmlns,则会被正确解析和查询。如果是这样,我们无法再通过标签和属性名称进行查询。但是,使用通配符和索引进行查询将会起作用。在Chrome中也是一样。创建和使用默认命名空间解析器以及自定义解析器没有帮助。任何建议?

If an XML document doesn't contain an xmlns, it gets parsed and queried correctly. If it does, we are not able to query by tag and attribute names anymore. However, querying with wildcards and indexes does work. The same is observed in Chrome. Creating and using default namespace resolver, as well as custom one, doesn't help. Any suggestions?

推荐答案

在处理命名空间时,您必须做两件事。

You have to do two things when dealing with namespaces.


  1. 在XPath表达式中使用命名空间。由于您的文档中没有前缀,所以我只是选择了 ns - 更好地了解现实世界代码中更具描述性的内容。

  2. 添加命名空间解析器,其实际上是作为第三个参数传递给 evaluate(...)的函数。

  1. Use the namespace in your XPath expression. As there is no prefix in your document, I just chose ns -- better go with something more descriptive in real world code.
  2. Add a namespace resolver, which actually is a function that gets passed as third parameter to evaluate(...).

将所有内容放在一起,您的代码将如下所示:

Putting everything together, your code would look like this:

parser = new DOMParser();
foo = parser.parseFromString('<foo xmlns="http://foo.bar.baz/quux"></foo>', "text/xml");
res = foo.evaluate("/ns:foo", foo, function(prefix) {
    if (prefix === 'ns') {
        return 'http://foo.bar.baz/quux';
    } else {
        return null
    }
}, 0, null);
res.iterateNext();

按预期返回:

<foo xmlns="http://foo.bar.baz/quux"></foo>






您的第三个查询具有结果,因为您正在使用通配符匹配器 * 忽略命名空间。没有注册命名空间,但使用通配符匹配器的另一种XPath表达式将是


Your third query has results because you're using the wildcard matcher * which ignores namespaces. An alternative XPath expression without registering a namespace, but using the wildcard matcher would be

//*[local-name() = 'foo']

这篇关于当给出xmlns时,DOM XPath查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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