如何用jQuery和JavaScript解析XML获取delivery=streaming的内容
用jQuery解析XML获取指定属性的MediaFile内容
需求
解析XML文档,获取delivery属性值为streaming的MediaFile标签中的CDATA内容。
示例XML
<MediaFiles> <MediaFile delivery="progressive" bitrate="3253252" type="video/mp4"><![CDATA[ https://file.mp4 ]]></MediaFile> <MediaFile delivery="streaming" bitrate="3253252" type="application/x-mpegURL"><![CDATA[ https://playlist.m3u8 ]]></MediaFile> </MediaFiles>
现有代码问题
现有AJAX请求存在两个关键问题:
- 参数
datatype拼写错误,jQuery AJAX要求驼峰命名的dataType,否则可能无法正确解析XML - 未对
MediaFile标签按delivery属性筛选,会获取所有标签内容
修正后的代码
$.ajax({ type: 'get', url: 'https://getxml.com?cb=' + new Date().getTime(), dataType: "xml", // 修正为驼峰命名的参数 success: function(data) { // 直接筛选delivery属性为streaming的MediaFile var streamingMedia = $(data).find('MediaFile[delivery="streaming"]'); // 获取第一个匹配项的内容 if (streamingMedia.length > 0) { var url = streamingMedia.text().trim(); // 去除CDATA前后空白字符 console.log('流媒体地址:', url); } // 若存在多个符合条件的标签,可收集所有内容 // var streamingUrls = []; // streamingMedia.each(function() { // streamingUrls.push($(this).text().trim()); // }); // console.log('所有流媒体地址:', streamingUrls); }, error: function(xhr, status, error) { console.error('XML请求失败:', error); } })
关键修改说明
- 属性选择器:用
MediaFile[delivery="streaming"]精准定位目标标签,无需遍历所有元素 - 参数修正:将
datatype改为dataType,确保jQuery正确识别并解析XML响应 - 内容提取:通过
text()获取CDATA内容,trim()清理多余空白字符
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

