使用jQuery解析XML之类的内容 [英] Parse content like XML, with jQuery

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

问题描述

我从一个输入值获得了此内容:

I have this content from one input value:

var xml_url  = $("input").val();
alert(xml_url);

输出:

<trans>
    <result>
        <item1>1</item1>
        <item2>content</item2>
        <item3>NA</item3>
        <item4>0</item1>
    </result>
</trans>

结构为XML文件.我想获取这些数据.

The structure is as a XML file. I want to get this data.

我有此代码:

<script language="javascript">
    $(document).ready(function(){
        var xml_url  = $("input").val();
          $(xml_url).find("result").each(function()  
          {         
            alert($(this).find("item3').").text());
          });
    });
</script>

它在Firefox中可以正常工作,但在IE7/8中却不能.

It works fine in firefox, but not in IE7/8.

有什么建议吗? 非常感谢.

Any suggestions? Thanks a lot.

推荐答案

从不依赖jQuery来解析XML.

Never rely on jQuery for parsing XML.

请参见

  • How do I parse xml with jQuery?
  • jQuery won't parse xml with nodes called option

使用适当的解析器来完成这项工作,然后使用jQuery查找所需的节点.您提供的示例适用于Firefox,但不适用于Chrome,Safari或IE.下面的函数将从字符串构造XML文档.

Use a proper parser to do the job, and then use jQuery to find the desired nodes. The example you gave works on Firefox, but not on Chrome, Safari or IE. The function below will construct a XML document from a string.

function parseXML(text) {
    var doc;

    if(window.DOMParser) {
        var parser = new DOMParser();
        doc = parser.parseFromString(text, "text/xml");
    }
    else if(window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = "false";
        doc.loadXML(text);
    }
    else {
        throw new Error("Cannot parse XML");
    }

    return doc;
}

用作:

// Parse and construct a Document object
var xml = parseXML(xml_url);

// Use jQuery on the object now
$(xml).find("result").each(function()  
{
    alert($(this).find("item3").text());
});

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

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