2010-07-02 2 views
1

인트라넷에서 외부 XML 피드를 활용하여 직원을보다 효율적으로 지원하고 콘텐츠 외부 네트워크로 이동할 필요성을 배웁니다.성가신 Youtube API XML 피드를 jQuery로 파싱

피드에서 기본 정보를 문제없이 렌더링 할 수 있습니다. 내가 멈추는 곳은 내가 선택한 레이아웃의 일부로 사용할 비디오 미리보기 이미지 중 하나를 표시하려고하는 것입니다.

내가 img 태그에 사용하기 위해 처음 media:thumbnail 요소에서 URL 속성 값을 잡기 위해 노력하고 있어요,하지만 난 그것의 내용을 렌더링 할 수없는 것하려고 어떤

문제.

예; <media:thumbnail url='http://i.ytimg.com/vi/CQP_AuT4zXQ/default.jpg'... />

내가 위의 예에서 & 사용을 추출 할 것 텍스트의 조각은 내가이 요소의 값을 구문 분석 할 수 아니에요 요소 함께 할 수있는 뭔가가 왜 http://i.ytimg.com/vi/CQP_AuT4zXQ/default.jpg

내가 생각입니다 그 안에 마침표 (:) 구분자가있는 이름 및/또는 jQuery에 대한 지식이 많아서이 요소 또는 그 일부를 올바르게 호출하거나 구문 분석하지 못한다고 의심됩니다.

또한 같은 문제를 이해하면 해결 될 media:keywords 값을 렌더링하고 싶습니다.

코드 파일이 잡고하게되는

을 구문 분석 유튜브에서

<script type="text/javascript"> 
/* learned from http://www.switchonthecode.com/tutorials/xml-parsing-with-jquery */ 
/* this can be used to parse any file in an XML format */ 
$(document).ready(function() 
{ 
/* 
perform an asynchronous ajax request using the relevant variables 
Documentation: http://api.jquery.com/jQuery.ajax/ 
*/ 
    $.ajax({ 
    type: "GET", 
    /* define url of xml file to parse */ 
    url: "/pr/rss_repository/youtube.xml", 
    /* assign it a data type */ 
    dataType: "xml", 
    /* state name of function to run if file is successfully parsed */ 
    success: parseXml 
    }); 
}); 
function parseXml(xml) 
/* this is where the xml file is parsed and converted into a HTML output */ 
{ 

    //for each item node in the xml file 
    $(xml).find("item").each(function() 
    { 
    //print the following html, inserting the relevant data within the nodes of item 
    //this is the heading 
    $("#output").append("<h2><a href=\"" + $(this).find("link").text() + "\" target=\"_blank\"> " + $(this).find("title").text() + "</a></h2>\n"); 
//this is a new paragraph with the publication date 
    $("#output").append("<p>" + $(this).find("pubDate").text() + "</p>\n"); 
//this is the description text of the item 
$("#output").append("<p>" + $(this).find("description").text() + "</p>\n"); 
$("#output").append("<p><img src=\"" + $(this).find("media:thumbnail").text() + "\"></p>\n"); 
    }); 
//end for each 
//end function 
} 
</script> 

결과 HTML

<h2><a href="http://www.youtube.com/watch?v=CQP_AuT4zXQ&amp;feature=youtube_gdata" target="_blank"> IFA World Forestry Day 2010 forum - Bob Pearce, FIFWA (Part 1)</a></h2> 
<p>Thu, 01 Apr 2010 06:44:19 +0000</p> 
<p>Bob Pearce, Executive Director - Forest Industries Federation of Western Australia delivers a presentation on the impact of timber harvesting in healthy forests at the Institute of Foresters of Australia 2010 World Forestry Day forum.</p> 
<p><img src=""></p> 
... 

에게 XML

을 렌더링하기 위해 XML의 샘플을 사용 여기에있는 우리의 서버는 파일은 호출 될 때마다 다운로드됩니다. 쿼리 된 URL에서 반환 된 내용을 덤프하는 VBScript를 사용하여 네트워크로 가져옵니다.

데이터의 예, http://gdata.youtube.com/feeds/api/videos?alt=rss&author=fpcwa에서 :

<?xml version='1.0' encoding='UTF-8'?> 
<rss xmlns:atom='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:gml='http://www.opengis.net/gml' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:georss='http://www.georss.org/georss' version='2.0'> 
    <channel> 
    ... standard channel description 
    <item> 
     <guid isPermaLink='false'>tag:youtube.com,2008:video:CQP_AuT4zXQ</guid> 
     <pubDate>Thu, 01 Apr 2010 06:44:19 +0000</pubDate> 
     <atom:updated>2010-04-29T00:03:31.000Z</atom:updated> 
     <category domain='http://schemas.google.com/g/2005#kind'>http://gdata.youtube.com/schemas/2007#video</category> 
     <category domain='http://gdata.youtube.com/schemas/2007/categories.cat'>News</category> 
     <category domain='http://gdata.youtube.com/schemas/2007/keywords.cat'>ifa</category> 
     ... remaining categories 
     <title>IFA World Forestry Day 2010 forum - Bob Pearce, FIFWA (Part 1)</title> 
     <link>http://www.youtube.com/watch?v=CQP_AuT4zXQ&feature=youtube_gdata</link> 
     <author>fpcwa</author> 
     <yt:accessControl action='comment' permission='allowed'/> 
     ... 
     <gd:comments> 
     <gd:feedLink href='http://gdata.youtube.com/feeds/api/videos/CQP_AuT4zXQ/comments?client=ytapi-google-jsdemo' countHint='0'/> 
     </gd:comments> 
     <media:group> 
     <media:category label='News & Politics' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>News</media:category> 
     <media:content url='http://www.youtube.com/v/CQP_AuT4zXQ?f=videos&c=ytapi-google-jsdemo&app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='587' yt:format='5'/> 
     <media:content url='rtsp://v1.cache6.c.youtube.com/CjcLENy73wIaLgl0zfjkAv8DCRMYDSANFEITeXRhcGktZ29vZ2xlLWpzZGVtb0gGUgZ2aWRlb3MM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='587' yt:format='1'/> 
     <media:content url='rtsp://v2.cache3.c.youtube.com/CjcLENy73wIaLgl0zfjkAv8DCRMYESARFEITeXRhcGktZ29vZ2xlLWpzZGVtb0gGUgZ2aWRlb3MM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='587' yt:format='6'/> 
     <media:credit role='uploader' scheme='urn:youtube'>fpcwa</media:credit> 
     <media:description type='plain'>Bob Pearce, Executive Director - Forest Industries Federation of Western Australia delivers a presentation on the impact of timber harvesting in healthy forests at the Institute of Foresters of Australia 2010 World Forestry Day forum.</media:description> 
     <media:keywords>ifa, institute of foresters, australia, forestry, world forestry day, 2010, forum, healthy forests, forest, forests, bob pearce, fifwa</media:keywords> 
     <media:player url='http://www.youtube.com/watch?v=CQP_AuT4zXQ&feature=youtube_gdata'/> 
     <media:thumbnail url='http://i.ytimg.com/vi/CQP_AuT4zXQ/default.jpg' height='90' width='120' time='00:04:53.500'/> 
     <media:thumbnail url='http://i.ytimg.com/vi/CQP_AuT4zXQ/2.jpg' height='90' width='120' time='00:04:53.500'/> 
     <media:thumbnail url='http://i.ytimg.com/vi/CQP_AuT4zXQ/1.jpg' height='90' width='120' time='00:02:26.750'/> 
     <media:thumbnail url='http://i.ytimg.com/vi/CQP_AuT4zXQ/3.jpg' height='90' width='120' time='00:07:20.250'/> 
     <media:thumbnail url='http://i.ytimg.com/vi/CQP_AuT4zXQ/hqdefault.jpg' height='360' width='480'/> 
     <media:title type='plain'>IFA World Forestry Day 2010 forum - Bob Pearce, FIFWA (Part 1)</media:title> 
     <yt:aspectRatio>widescreen</yt:aspectRatio> 
     <yt:duration seconds='587'/> 
     <yt:uploaded>2010-04-01T06:44:19.000Z</yt:uploaded> 
     <yt:videoid>CQP_AuT4zXQ</yt:videoid> 
     </media:group> 
     <yt:statistics favoriteCount='0' viewCount='10'/> 
    </item> 
+1

궁금한 점이 있다면 [JSON 버전의 YouTube API] (http://code.google.com/apis/youtube/2.0/developers_guide_json.html)를 사용하는 것이 훨씬 간단할까요? :) –

+0

생각이 내 마음을 넘어, 나는이 두 가지 작업을 위해 지금 실험 중이다. JSON을 사용하면서 저를 대손점으로 생각하는 이유 중 하나는 모든 데이터가 한 줄에 있기 때문에 JSON 데이터 세트를 읽을 수 없다는 것입니다. – thewinchester

+0

단지 dataType : "xml"을 dataType : "json"으로 변경하면 멋진 객체가 생깁니다. 주제에서 벗어난 – levhita

답변

2

이것은 처리 XML 네임 스페이스를 지원하지 않습니다 jQuery를, 버그입니다. 다음 두 가지 방법 중 하나를 사용할 수 있습니다.

.find("[nodeName=media:thumbnail]") 
.find("media\\:thumbnail]") 

대부분의 사람들은 특정 WebKit 버전에서 두 번째 방법이 작동하지 않으므로 첫 번째 방법을 권장합니다.

자세한 내용이나 다른 대안이 필요하면 웹에서 "jquery find namespace"을 검색하십시오.

업데이트은 다음 media:thumbnail 노드의 ulr 속성의 값을 얻으려면, 다음을 사용 :

.attr("url") 
+0

빠른 답변 주셔서 감사합니다. - 올바른 방향으로 나를 안내해 드리지만, 원래 질문에서 오류를 강조 표시합니다 (이를 반영하여 업데이트 됨). 얻으려고하는'media : thumbnail' 부분은 일반적인 ''내에 포함되지 않고'', 특히 URL 속성과 연관된 텍스트, 예 : '' – thewinchester