在JavaScript中对XML变量进行XML解析 [英] XML parsing of a variable string in JavaScript

查看:122
本文介绍了在JavaScript中对XML变量进行XML解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量字符串,其中包含格式良好且有效的XML。我需要使用JavaScript代码来解析此Feed。

I have a variable string that contains well-formed and valid XML. I need to use JavaScript code to parse this feed.

如何使用(浏览器兼容的)JavaScript代码完成此操作?

How can I accomplish this using (browser-compatible) JavaScript code?

推荐答案

更新:有关更正确的答案,请参阅 Tim Down的回答

Update: For a more correct answer see Tim Down's answer.

Internet Explorer以及(例如)基于Mozilla的浏览器为XML解析公开了不同的对象,因此使用像 jQuery 来处理跨浏览器的差异。

Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like jQuery to handle the cross-browsers differences.

一个非常基本的例子是:

A really basic example is:

var xml = "<music><album>Beethoven</album></music>";

var result = $(xml).find("album").text();

注:正如评论中指出的那样; jQuery并没有真正做任何XML解析,它依赖于DOM innerHTML方法,并且会解析它就像任何HTML一样,因此在XML中使用HTML元素名称时要小心。但我认为它对于简单的XML解析非常有用,但它可能不建议用于密集或动态XML解析,在这种情况下,您不会预先知道XML将会发生什么,并且测试是否所有内容都按预期进行解析。

Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.

这篇关于在JavaScript中对XML变量进行XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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