使用IE,FF和chrome中的命名空间读取xml [英] Read xml with namespace in IE, FF and chrome

查看:83
本文介绍了使用IE,FF和chrome中的命名空间读取xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下带有名称空间的xml响应.

I have the below xml response with namespace.

<?xml version="1.0"?>
<response status="200">
  <ns3:op xmlns="http://xxx.com/details/" 
              xmlns:ns2="http://xxx.com/mgmt/" 
              xmlns:ns3="http://xxx.com/list/">
    <ns2:ntfs count="140">
      <ns2:ntf>
        <ns2:Nid>4687807</ns2:Nid>
      </ns2:ntf>
    </ns2:ntfs>
  </ns3:op>
</response>

我需要对此进行解析,并获取每一行的Nid值.我尝试使用getElementsByTagName(ns3:op),但在野生动物园中不起作用. 也尝试使用 xmlDoc.documentElement.selectNodes("/response/op/ntfs"); 但是它在FF中不起作用. 有什么方法可以使我独立于名称空间和浏览器读取响应.

I need to parse this and get the Nid value for each row. I tried using getElementsByTagName(ns3:op) but it doesnt work in safari. Also tried using xmlDoc.documentElement.selectNodes("/response/op/ntfs"); But it is not working in FF. is there any way where i can read the response independent of namespace and browser.

我的输出xml可能会更改,并且元素可能具有或不具有名称空间前缀. 因此,无论命名空间如何,我都需要解析xml. 我怎样才能做到这一点? 这对我来说并不紧急,任何指针都将不胜感激.

My output xml might change and the elements may or may not have namespace prefixes. So i need to parse the xml irrespective of the namespace. How can i achieve this? This is little urgent to me , any pointers would be grateful.

推荐答案

对于命名空间,您需要对命名空间URI使用getElementsByTagNameNS

With namespaces you need to use getElementsByTagNameNS with the namespace URI

document.getElementsByTagNameNS('http://xxx.com/list/', 'op')

但是,这显然在9之前的IE中不起作用.通常推荐的跨浏览器解决方案是 Sarissa ,一个JavaScript库,该库以一种可在更多浏览器上使用的方式实现XPath方法:

However this apparently doesn't work in IE earlier than 9. A commonly recommended cross browser solution is Sarissa, a JavaScript library which implements the XPath approach in a way that works on more browsers:

var xmlDoc = new DOMParser().parseFromString(....);
xmlDoc.setProperty("SelectionNamespaces", 'xmlns:ns3="http://xxx.com/list/"');
xmlDoc.setProperty("SelectionLanguage", "XPath");
var op = xmlDoc.selectSingleNode("/response/ns3:op");

这篇关于使用IE,FF和chrome中的命名空间读取xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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