【问题标题】:Extracting XML data using javascript使用 javascript 提取 XML 数据
【发布时间】:2013-09-26 19:30:15
【问题描述】:
   <!--  http://www.abc.com  -->
    <rss version="2.0">
    <channel>
    <title>SENSEX view</title>
    <link>http://www.abc.com</link>
    <copyright>Copyright 2009, abc</copyright>
    <item>
    <title>
    <![CDATA[ SENSEX : 20263.71 * -382.93 (-1.85 %) ]]>
    </title>
    <link/>
    <pubDate>9/20/2013 4:00:00 PM</pubDate>
    <author>abc</author>
    <guid/>
    </item>
    </channel>
    </rss>

我想从变量中的上述 XML 数据中提取“&lt;![CDATA[ SENSEX : 20263.71 * -382.93 (-1.85 %) ]]&gt;”。我不熟悉使用 javascript 处理 XML。所以我需要一些帮助或建议我一些教程??

这是我得到的:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script>
$(document).ready(function(){
$.ajax({
    type: "GET",
    url: "http://rss.xml",
    dataType: "xml",.find("title")
    success: function(xml) {
        $(xml).find("title").each(function(){

            var title = $(this).find('title').text();
            $(this).find('title').each(function()
            {
                alert(title );

            });
        });
    }
});
});
</script>
</head>
<body> 
</body>
</html>

【问题讨论】:

  • 您的代码正在尝试查找“站点”,它不是您的 xml 中的元素,也没有任何名为“id”的属性,如果您想要“标题”数据使用.find("title")跨度>
  • 您似乎需要 title 元素中存在的 each item 元素的内容。那里有线索:)
  • 谢谢你们!它有效:)
  • 不使用jquery有什么办法吗??
  • @Alfred 是的,看我的回答。

标签: javascript jquery html xml ajax


【解决方案1】:

将您的 success 回调代码更改为:

success: function(xml) {
         $(xml).find('item').each(function(){
                 $(this).find('title').each(function(){
         var title = $(this).text();
         alert(title);
       });
       });
    }

并且没有 jQuery:

xmlDoc=loadXMLDoc("yourFile.xml");
var title = xmlDoc.getElementsByTagName("title")[0];
alert(title);

function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

【讨论】:

  • 不使用jquery有什么办法吗??
  • '
    '
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 2010-12-04
  • 2015-01-19
  • 2015-03-28
相关资源
最近更新 更多