Как использовать xslt для перехода по RSS-каналу и отображения только нужной информации - PullRequest
0 голосов
/ 20 ноября 2011

Я хочу посмотреть на внешний RSS-канал и отобразить его на моем сайте, но там есть некоторая избыточная информация, которую я не хочу, и я также хочу добавить свой собственный контент, зависящий от содержимого XML.

Чтобы попытаться прояснить мое объяснение, приведем пример фиктивной ленты новостей, включающей текущий день недели и время. Затем я хотел бы добавить это, отфильтровать время, чтобы просто иметь день недели, и заменить его изображением, относящимся к дню недели.

Редактировать: Хорошо, вот возможный пример: Yahoo - погода сегодня rss

Показывает текущую погоду в Лондоне (вместе с кратким прогнозом). Как бы я посмотрел на атрибут text узла yweather: condition и отобразил изображение, относящееся к нему, так что, если бы оно говорило «Туман», как это происходит в настоящее время, я бы отобразил изображение тумана, если оно говорит «солнце», изображение солнце и т. д.

1 Ответ

1 голос
/ 20 ноября 2011

Используйте :

/*/*/item/yweather:condition/@text

, где вы зарегистрировали в PL (на котором размещен механизм XPath) префикс "yweather", связанный с пространством имен "http://xml.weather.yahoo.com/ns/rss/1.0".

XSLT-проверка :

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
 exclude-result-prefixes="yweather">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
     <img src="{/*/*/item/yweather:condition/@text}.jpg"/>
 </xsl:template>
</xsl:stylesheet>

применительно к документу XML, на который указывает ссылка в вопросе :

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
    <channel>
        <title>Yahoo! Weather - London, GB</title>
        <link>http://us.rd.yahoo.com/dailynews/rss/weather/London__GB/*http://weather.yahoo.com/forecast/UKXX0085_c.html</link>
        <description>Yahoo! Weather for London, GB</description>
        <language>en-us</language>
        <lastBuildDate>Sun, 20 Nov 2011 2:50 pm GMT</lastBuildDate>
        <ttl>60</ttl>
        <yweather:location city="London" region=""   country="United Kingdom"/>
        <yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/>
        <yweather:wind chill="7"   direction="0"   speed="3.22" />
        <yweather:atmosphere humidity="100"  visibility="0.9"  pressure="1015.92"  rising="0" />
        <yweather:astronomy sunrise="7:26 am"   sunset="4:05 pm"/>
        <image>
            <title>Yahoo! Weather</title>
            <width>142</width>
            <height>18</height>
            <link>http://weather.yahoo.com</link>
            <url>http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif</url>
        </image>
        <item>
            <title>Conditions for London, GB at 2:50 pm GMT</title>
            <geo:lat>51.51</geo:lat>
            <geo:long>-0.13</geo:long>
            <link>http://us.rd.yahoo.com/dailynews/rss/weather/London__GB/*http://weather.yahoo.com/forecast/UKXX0085_c.html</link>
            <pubDate>Sun, 20 Nov 2011 2:50 pm GMT</pubDate>
            <yweather:condition  text="Mostly Cloudy"  code="28"  temp="7"  date="Sun, 20 Nov 2011 2:50 pm GMT" />
            <description><![CDATA[
<img src="http://l.yimg.com/a/i/us/we/52/28.gif"/><br />
<b>Current Conditions:</b><br />
Mostly Cloudy, 7 C<BR />
<BR /><b>Forecast:</b><BR />
Sun - Cloudy. High: 9 Low: 8<br />
Mon - Mostly Cloudy. High: 12 Low: 10<br />
<br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/London__GB/*http://weather.yahoo.com/forecast/UKXX0085_c.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>
(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>
]]></description>
            <yweather:forecast day="Sun" date="20 Nov 2011" low="8" high="9" text="Cloudy" code="26" />
            <yweather:forecast day="Mon" date="21 Nov 2011" low="10" high="12" text="Mostly Cloudy" code="28" />
            <guid isPermaLink="false">UKXX0085_2011_11_21_7_00_GMT</guid>
        </item>
    </channel>
</rss>
<!-- api9.weather.ac4.yahoo.com compressed/chunked Sun Nov 20 07:44:04 PST 2011 -->

дает желаемый результат :

<img src="Mostly Cloudy.jpg"/>

Обновление : ОП теперь предоставил в комментарии точный желаемый результат.Ниже приведено преобразование, которое создает этот вывод:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0"
 exclude-result-prefixes="yweather">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
    <xsl:text
    disable-output-escaping="yes">&lt;!DOCTYPE HTML></xsl:text>
    <xsl:text>&#xA;</xsl:text>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        </head>
        <body>
            <div id="weather">
                  <img src="{/*/*/item/yweather:condition/@text}.jpg"/>
            </div>
        </body>
    </html> 
 </xsl:template>
</xsl:stylesheet>

, когда это преобразование применяется к тому же XML-документу (см. Выше), будет получен требуемый результат:

<!DOCTYPE HTML>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
   </head>
   <body>
      <div id="weather">
         <img src="Mostly Cloudy.jpg"/>
      </div>
   </body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...