使用 Javascript 将 xml 加载到类 [英] Loading a xml to a class with Javascript

查看:37
本文介绍了使用 Javascript 将 xml 加载到类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Javascript 将 XML 文件加载到类中?

How can I load a XML file to class using Javascript?

推荐答案

不幸的是,每个浏览器都有自己的解析包含 XML 的字符串的方法.以下是我所知道的三大浏览器的方法.请注意,我没有机会尝试每一个,因为它们是从各种博客和我自己的记忆中拼凑而成的.

Unfortunately, each browser presents its own way of parsing a string containing XML. Here are the ways that I know of for each of the big 3 browsers. Please note, I haven't had a chance to try each of these as they're cobbled together from various blogs and my own memory.

Firefox 有一个名为 DOMParser 的对象,可用于解析字符串中的 XML.API 非常简单——实例化DOMParser 并调用它的parseFromString 方法.下面是一个例子:

Firefox has an object called DOMParser that can be used to parse XML in a string. The API is pretty simple -- instantiate the DOMParser and call its parseFromString method. Here is an example:

var xmlString = '<?xml version="1.0"?>...';
var parser = new DOMParser();
var dom = parser.parseFromString(theString, "text/xml");
// use dom

IE 使用 Microsoft ActiveX XMLDOM 控件,因此您必须实例化 DOM 控件并使用其方法,再举个例子:

IE uses the Microsoft ActiveX XMLDOM control, therefore you must instantiate the DOM control and use its methods, again here's an example:

var xmlString = '<?xml version="1.0"?>...';
dom=new ActiveXObject("Microsoft.XMLDOM");
dom.async="false";
dom.loadXML(xmlString);
// use dom

最后是奇怪的 Safari 版本.Safari 没有内置解析器,因为它不能在 Windows 上运行,所以它不支持 ActiveX 控件.但是,Safari 确实支持 data: 网址.在 Safari 中,会创建一个包含文档的 URL,并通过 XMLHTTPRequest 调用.与所有 XMLHttpRequest 一样,您可以使用 XMLHttpRequest 的标准 responseXml 属性来访问 DOM.

And lastly, the weirdo Safari version. Safari doesn't have a parser built in, and being that it doesn't run on Windows it doesn't support ActiveX controls. However, Safari does support data: urls. In Safari a URL with the document is created and called through an XMLHTTPRequest. Like all XMLHttpRequests, you use the standard responseXml property of the XMLHttpRequest to access the DOM.

var xmlString = '<?xml version="1.0"?>...';
var url = "data:text/xml;charset=utf-8," + encodeURIComponent(xmlString);

var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send(null);

var dom = xhr.responseXML;
// Use dom here

这篇关于使用 Javascript 将 xml 加载到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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