2012-07-20 61 views
0

我有一些JavaScript應該從XML文檔中使用以下代碼獲取此圖像URL [1]。但Chrome的控制檯在此行上返回Uncaught TypeError: Cannot read property '1' of null。正則表達式是否不正確?使用JQuery提取XML中的圖像鏈接

var image = $(post.description.match(/<br\/>(<a.*><img.*<\/a>)<br\/>/)[1]).addClass('photo'); 

[1] http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/391316_483838581645230_1080523933_s.jpg

的XML的結構,像這樣:

<description> 
<![CDATA[ 
Extendemos una cordial felicitación a Reserva de la Biosfera Banco Chinchorro que celebra su aniversario el día de hoy. 
Un especial saludo a Maricarmen García, Directora de la Reserva y Líder 2010 del Programa de Liderazgo. ¡Estamos muy 
orgullosos de su trabajo!<br /> <br /> We would like to co 
]]> 
<![CDATA[ 
ngratulate Banco Chinchorro Biosphere Reserve who is celebrating their anniversary today. A special greeting to Maricarmen 
García, the Reserve&#039;s Director and 2010 MAR Leadership Fellow. We are so proud of your work!<br /> <br /> 
<a href="http://pyucatan.conanp.gob.mx/chincho.htm" target="_blank" rel="nofollow nofollow" 
onmousedown="UntrustedLink.bootstrap($(this), &quot;HAQE2sh3f&quot;, event, bagof({}));">http://pyucatan.conanp.gob.mx/chincho.htm</a><br/><br/> 
<a href="http://www.facebook.com/photo.php?fbid=483838581645230&amp;set=a.167790786583346.41662.123942950968130&amp;type=1&amp;relevant_count=1" 
title="" target=""><img class="img" src="http://photos-c.ak.fbcdn.net/hphotos-ak-ash4/391316_483838581645230_1080523933_s.jpg" alt="" /></a> 
]]> 
</description> 
+0

由於圖像URL是節點內的字符串中,所以我仍舊需要通過它來解析解析。 – Simpleton 2012-07-20 09:42:40

+0

我正在獲取該XML。 – Simpleton 2012-07-20 09:49:57

+0

@AlvinWong:是否需要轉義那些CDATA部分? – Bergi 2012-07-20 09:51:44

回答

2

是正則表達式不正確的?

是的。 /<br\/>(<a.*><img.*<\/a>)<br\/>/嘗試匹配沒有空格的br標籤,並且在您給我們的字符串中也沒有鏈接後的<br>。所以,比賽返回null並且沒有財產「1」。

無論如何,Regex is not suited這個任務。只是讓你<description>節點的textContent,解析它作爲HTML使用jQuery(見Can jQuery Parse HTML Stored in a Variable?),甚至爲X [HT] ML與jQuery.parseXML,並使用selector to geta > img元素出來,以閱讀src屬性。