How can I parse a YouTube URL using XSLT?

I would like to parse the youtube url using XSLT and get only the video id from that url. What is the best way to do this with XSLT?

So, if url: http://www.youtube.com/watch?v=qadqO3TOvbQ&feature=channel&list=UL

I only want qadqO3TOvbQ and put it in the embed code:

 <iframe width="560" height="315" src="http://www.youtube.com/embed/qadqO3TOvbQ" frameborder="0" allowfullscreen=""></iframe> 
+6
source share
2 answers

XSLT / XPath is not suitable for string processing (especially 1.0), but you can achieve what you need by mixing the substring-after() and substring-before() functions:

 <xsl:value-of select="substring-before(substring-after($yt_url, '?v='), '&amp;feature')" /> 

(It is assumed that the YT URL is stored in the XSLT variable, $yt_url and that it has & c &amp; ).

Demo on this XML playground

+3
source

I. This is an XPath 2.0 expression :

 substring-after(tokenize($pUrl, '[?|&amp;]')[starts-with(., 'v=')], 'v=') 

creates the desired, correct result .

Alternatively, you can use a little shorter:

 tokenize(tokenize($pUrl, '[?|&amp;]')[starts-with(., 'v=')], '=')[2] 

Here is the complete transformation of XSLT 2.0 :

 <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:param name="pUrl" select= "'http://www.youtube.com/watch?v=qadqO3TOvbQ&amp;feature=channel&amp;list=UL'"/> <xsl:template match="/"> <xsl:sequence select= "tokenize(tokenize($pUrl, '[?|&amp;]')[starts-with(., 'v=')], '=')[2]"/> </xsl:template> </xsl:stylesheet> 

When this conversion is applied to any XML document (not used), the desired, correct result is obtained :

 qadqO3TOvbQ 

II. This is an XPath 1.0 expression :

  concat (substring-before(substring-after(concat($pUrl,'&amp;'),'?v='),'&amp;'), substring-before(substring-after(concat($pUrl,'&amp;'),'&amp;v='),'&amp;') ) 

creates the desired result .

Please note :

Both solutions retrieve the desired string, even if the query string parameter named v not the first, or even if it is the last.

+4
source

Source: https://habr.com/ru/post/919947/


All Articles