用Javascript解析XML [英] XML Parsing in Javascript

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

问题描述

我试图解析来自XMLHttpRequest(用于Firefox扩展)的xml。在下面的代码中,req是一个XMLHttpRequest对象。在声明req之后,我做了 req.overrideMimeType(text / xml);

  var shortURL; 
var xmlDoc = document.implementation.createDocument(,,null);
xmlDoc.async = false;
xmlDoc = req.responseXml;
if(xmlDoc.readyState == 4){
shortURL = xmlDoc.documentElement.childNodes [8] .text;如果我使用 req.responseXml
$ / code>

$ c>如果我使用 req.responseText xmlDoc = req.responseXml;我得到一个错误,提示xmlDoc没有声明 / code>, xmlDoc.readyState == 4 变成false。

的JavaScript,所以请告诉我,如果我在这里做错了什么。

解决方案

我通常更喜欢使用 responseText ,然后使用浏览器内置的XML解析库来解析XML。之后,我通常会将生成的XML文档树或子树转换为JSON,以方便在JavaScript中访问。



我为此写了一个小实用程序库:



http://earth-api-samples.googlecode.com/svn/trunk/demos/myearth/lib/xmlutil.js



使用非常简单:

$ p $ var json = xmlNodeToJson(parseXml(req.responseText);


I'm trying to parse an xml coming from an XMLHttpRequest (for a Firefox extension). In the following code, req is an XMLHttpRequest object. I did req.overrideMimeType("text/xml"); after declaring req.

var shortURL;  
var xmlDoc = document.implementation.createDocument("","",null);  
xmlDoc.async = false;  
xmlDoc = req.responseXml;  
if (xmlDoc.readyState == 4){  
    shortURL = xmlDoc.documentElement.childNodes[8].text;  
}

If I use req.responseXml I get an error saying "xmlDoc is not declared" for the line after xmlDoc = req.responseXml; If I use req.responseText, xmlDoc.readyState == 4 turns false.

I don't do much of javascript so please tell me if I'm doing something wrong here.

解决方案

I generally prefer using responseText and then parsing the XML using the browser's built in XML parsing library. After that, I generally convert the resulting XML document tree, or a sub tree, to JSON for easy access in JavaScript.

I wrote a tiny utility library for this here:

http://earth-api-samples.googlecode.com/svn/trunk/demos/myearth/lib/xmlutil.js

The usage is pretty simple:

var json = xmlNodeToJson(parseXml(req.responseText);

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

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