Как получить первую температуру в xml как высокую, а вторую как низкую

Предоставленный xml представляет собой прогноз дня/ночи на 2 дня. Мне нужно установить все остальные температуры на высокую температуру, а остальные на низкую. Я новичок и хотел бы знать, как я могу сделать это в xsl. Я думал что-то сделать со временем суток, но не уверен. Заранее благодарны за Вашу помощь.

пример кода xml ниже.

`

<forecast>
-<dailyForecastPeriods>
<cloudCoverPercent>58</cloudCoverPercent>
<dewPoint>51.8</dewPoint>
<iconCode>3</iconCode>
<precipCode>1</precipCode>
<precipProbability>0</precipProbability>
<relativeHumidity>50</relativeHumidity>
<summaryDescription>Partly Cloudy</summaryDescription>
<temperature>78</temperature>
<thunderstormProbability>0</thunderstormProbability><windDirectionDegrees>92</windDirectionDegrees>
<windSpeed>4.5</windSpeed>
<detailedDescription>Partly cloudy. Highs in the upper 70s. Southeast winds around 5 mph...Becoming east around 5 mph this afternoon. </detailedDescription><forecastDateLocalStr>2014-07-18T07:00:00</forecastDateLocalStr><forecastDateUtcStr>2014-07-18T11:00:00Z</forecastDateUtcStr><isNightTimePeriod>false</isNightTimePeriod>
</dailyForecastPeriods>-<dailyForecastPeriods>
<cloudCoverPercent>98</cloudCoverPercent>
<dewPoint>59</dewPoint>
<iconCode>81</iconCode>
<precipCode>1</precipCode>
<precipProbability>75</precipProbability>
<relativeHumidity>65</relativeHumidity>
<summaryDescription>30% Chance of Rain</summaryDescription>
<temperature>60</temperature>
<thunderstormProbability>10</thunderstormProbability><windDirectionDegrees>99</windDirectionDegrees>
<windSpeed>6.7</windSpeed>
<detailedDescription>Partly cloudy in the evening...Then mostly cloudy with a chance of showers after midnight. Lows around 60. East winds 5 to 10 mph...Becoming southeast after midnight. Chance of rain 30 percent. </detailedDescription><forecastDateLocalStr>2014-07-18T19:00:00</forecastDateLocalStr><forecastDateUtcStr>2014-07-18T23:00:00Z</forecastDateUtcStr><isNightTimePeriod>true</isNightTimePeriod>
</dailyForecastPeriods>-<dailyForecastPeriods>
<cloudCoverPercent>83</cloudCoverPercent>
<dewPoint>64.4</dewPoint>
<iconCode>89</iconCode>
<precipCode>1</precipCode>
<precipProbability>75</precipProbability>
<relativeHumidity>79</relativeHumidity>
<summaryDescription>50% Chance of Rain</summaryDescription>
<temperature>80</temperature>
<thunderstormProbability>30</thunderstormProbability><windDirectionDegrees>175</windDirectionDegrees>
<windSpeed>8.9</windSpeed>
<detailedDescription>Cloudy with a chance of showers. Highs in the upper 70s. Southeast winds 5 to 10 mph. Chance of rain 50 percent. </detailedDescription><forecastDateLocalStr>2014-07-19T07:00:00</forecastDateLocalStr><forecastDateUtcStr>2014-07-19T11:00:00Z</forecastDateUtcStr><isNightTimePeriod>false</isNightTimePeriod>
</dailyForecastPeriods>-<dailyForecastPeriods>
<cloudCoverPercent>62</cloudCoverPercent>
<dewPoint>64.4</dewPoint>
<iconCode>82</iconCode>
<precipCode>1</precipCode>
<precipProbability>45</precipProbability>
<relativeHumidity>84</relativeHumidity>
<summaryDescription>40% Chance of Rain</summaryDescription>
<temperature>64</temperature>
<thunderstormProbability>10</thunderstormProbability><windDirectionDegrees>169</windDirectionDegrees>
<windSpeed>4.5</windSpeed>
<detailedDescription>Mostly cloudy with a chance of showers. Lows in the lower 60s. Southeast winds 5 to 10 mph. Chance of rain 40 percent. </detailedDescription><forecastDateLocalStr>2014-07-19T19:00:00</forecastDateLocalStr><forecastDateUtcStr>2014-07-19T23:00:00Z</forecastDateUtcStr><isNightTimePeriod>true</isNightTimePeriod>
</dailyForecastPeriods>
</forecast>

`

Sample of xsl
`

<xsl:template match="//forecast">
    <xsl:choose>
      <xsl:when test="//CUSTOM/WEATHER/TYPE='Compact'" />
      <xsl:otherwise>
        <xsl:if test="//CUSTOM/WEATHER/HIDE_EXTFORECAST='false'">
          <div class="rnd_grouping" style="cursor:pointer;text-align:center;" onclick="javascript:ShowHideSubmodule('extendedForecast', 'upDownForecast', '//MODULE[@id=\'B253588A-437D-4C8E-8BB4-CACA5506567D\']/SUBMODULE/@expanded', true);">
            <xsl:text>Extended Forecast</xsl:text>
          </div>
          <table width="100%" border="0" cellSpacing="0" cellPadding="0" id="extendedForecast">
            <xsl:variable name="startIndex">
              <xsl:choose>
                <xsl:when test="//CUSTOM/WEATHER/SHOWTODAY='true'">
                  0
                </xsl:when>
                <xsl:otherwise>
                  1
                </xsl:otherwise>
              </xsl:choose>
            </xsl:variable>
            <xsl:variable name="showToday">
              <xsl:choose>
                <xsl:when test="//CUSTOM/WEATHER/SHOWTODAY='true'">
                  0
                </xsl:when>
                <xsl:otherwise>
                  1
                </xsl:otherwise>
              </xsl:choose>
            </xsl:variable>
            <xsl:variable name="numDays">
              <xsl:choose>
                <xsl:when test="$devicetype='mobile'">

                </xsl:when>
                <xsl:otherwise>
                  <xsl:value-of select="//CUSTOM/WEATHER/NUMDAYS"/>
                </xsl:otherwise>
              </xsl:choose>
            </xsl:variable>
            <xsl:if test="//SUBMODULE[@type='Weather']/@expanded=0">
              <xsl:attribute name="style">
                display:none;
              </xsl:attribute>
            </xsl:if>
            <tr>
              <xsl:for-each select="//forecast/dailyForecastPeriods">
                <xsl:if test="position() > $startIndex">
                  <xsl:if test="position() &lt;= ($numDays)+$startIndex">
                    <td title="{detailedDescription}" align="center" valign="top" class="weatherforecastday">
                      <xsl:attribute name="width">
                        <xsl:value-of select="(100 div ($numDays)-$showToday)"/>
                        <xsl:text disable-output-escaping="yes">%</xsl:text>
                      </xsl:attribute>
                      <xsl:choose>
                        <xsl:when test="position()=1">Today</xsl:when>
                        <xsl:otherwise>
                          <!--<xsl:value-of select="dayoftheweek"></xsl:value-of>-->
                        </xsl:otherwise>
                      </xsl:choose>
                    </td>
                  </xsl:if>
                </xsl:if>
              </xsl:for-each>
            </tr>
            <tr>
              <xsl:for-each select="//forecast/dailyForecastPeriods">
                <xsl:if test="position() > $startIndex">
                  <xsl:if test="position() &lt;= ($numDays)+$startIndex">
                    <td title="{detailedDescription}" align="center" valign="top" class="weatherforecastimage">
                      <xsl:attribute name="width">
                        <xsl:value-of select="(100 div ($numDays)-$showToday)"/>
                        <xsl:text disable-output-escaping="yes">%</xsl:text>
                      </xsl:attribute>
                      <img src="{img_small}" />
                    </td>
                  </xsl:if>
                </xsl:if>
              </xsl:for-each>
            </tr>
            <tr>
              <xsl:for-each select="//forecast/dailyForecastPeriods">
                <xsl:if test="position() > $startIndex">
                  <xsl:if test="position() &lt;= ($numDays)+$startIndex">
                    <td title="{detailedDescription}" align="center" valign="top" class="weatherforecasttext">
                      <xsl:attribute name="width">
                        <xsl:value-of select="(100 div ($numDays)-$showToday)"/>
                        <xsl:text disable-output-escaping="yes">%</xsl:text>
                      </xsl:attribute>
                      <xsl:value-of select="summaryDescription"></xsl:value-of>
                    </td>
                  </xsl:if>
                </xsl:if>
              </xsl:for-each>
            </tr>
            <tr>
              <xsl:for-each select="//forecast/dailyForecastPeriods">
                <xsl:if test="position() > $startIndex">
                  <xsl:if test="position() &lt;= ($numDays)+$startIndex">
                    <td title="{detailedDescription}" align="center" valign="top" class="weatherforecasttemp">
                      <span class="weatherforecasthigh">
                        <xsl:value-of select="temperature[1]"/>
                        <xsl:text>°</xsl:text>                     
                      </span>
                      <xsl:text>&#160;</xsl:text>
                      <span class="weatherforecastlow">
                        <xsl:value-of select="temperature[2]" />
                        <xsl:text>°</xsl:text>
                      </span>
                    </td>
                  </xsl:if>
                </xsl:if>
              </xsl:for-each>
            </tr>

`


person smiller48    schedule 18.07.2014    source источник
comment
Пожалуйста, будьте немного внимательнее к форматированию. Было бы неплохо предоставить SSCCE, то есть полный файл XML и полный файл XSL, а не только его части.   -  person Thomas Weller    schedule 18.07.2014
comment
Я удалил свой ответ. Пожалуйста, отредактируйте свой вопрос и предоставьте полный и правильно сформированный пример вашего ввода XML.   -  person michael.hor257k    schedule 18.07.2014
comment
Были предоставлены дополнительные xml и xsl.   -  person smiller48    schedule 18.07.2014
comment
Всегда ли будет 4 периода, по 2 на свидание? Ваш XSLT - беспорядок, и не совсем ясно, какой результат вы хотите здесь получить.   -  person michael.hor257k    schedule 18.07.2014
comment
Какая версия XSLT?   -  person Daniel Haley    schedule 18.07.2014
comment
1.0. это 10-дневный прогноз, поэтому полный xml показывает 20 периодов по 2 на дату. У xsl есть изображение, и под изображением мне нужно, чтобы оно отображало высокую температуру дня и низкую температуру дня. Первый период — день, второй — ночь. Температура[1] должна равняться высокой температуре, температура[2] должна равняться низкой температуре.   -  person smiller48    schedule 18.07.2014
comment
Извините за путаницу, я пытаюсь быть настолько ясным, насколько могу.   -  person smiller48    schedule 18.07.2014


Ответы (1)


Предоставленный xml представляет собой прогноз дня/ночи на 2 дня. Мне нужно установить все остальные температуры на высокую температуру, а остальные на низкую.

Это может быть достигнуто довольно легко:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <table>
        <tr>
            <th>Date</th>
            <th>High</th>
            <th>Low</th>
        </tr>
        <tr>
            <td><xsl:value-of select="substring-before(forecast/dailyForecastPeriods[1]/forecastDateLocalStr, 'T')"/></td>
            <td><xsl:value-of select="forecast/dailyForecastPeriods[1]/temperature"/></td>
            <td><xsl:value-of select="forecast/dailyForecastPeriods[2]/temperature"/></td>
        </tr>
        <tr>
            <td><xsl:value-of select="substring-before(forecast/dailyForecastPeriods[3]/forecastDateLocalStr, 'T')"/></td>
            <td><xsl:value-of select="forecast/dailyForecastPeriods[3]/temperature"/></td>
            <td><xsl:value-of select="forecast/dailyForecastPeriods[4]/temperature"/></td>
        </tr>
    </table>
</xsl:template>

</xsl:stylesheet>

Или, если хотите (подойдет любое четное количество dailyForecastPeriods):

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <table>
        <tr>
            <th>Date</th>
            <th>High</th>
            <th>Low</th>
        </tr>
        <xsl:for-each select="forecast/dailyForecastPeriods[position() mod 2 = 1]">
            <tr>
                <td><xsl:value-of select="substring-before(forecastDateLocalStr, 'T')"/></td>
                <td><xsl:value-of select="temperature"/></td>
                <td><xsl:value-of select="following-sibling::dailyForecastPeriods[1]/temperature"/></td>
            </tr>
        </xsl:for-each>     
    </table>
</xsl:template>

</xsl:stylesheet>

Учитывая ваш отредактированный ввод, результатом будет:

<?xml version="1.0" encoding="UTF-8"?>
<table>
   <tr>
      <th>Date</th>
      <th>High</th>
      <th>Low</th>
   </tr>
   <tr>
      <td>2014-07-18</td>
      <td>78</td>
      <td>60</td>
   </tr>
   <tr>
      <td>2014-07-19</td>
      <td>80</td>
      <td>64</td>
   </tr>
</table>

отображается как:

введите здесь описание изображения

person michael.hor257k    schedule 18.07.2014
comment
По какой-то причине это не работает. Я попробовал это и ‹xsl:value-of select = Temperature[position()= 2]/› - person smiller48; 18.07.2014
comment
Большое спасибо! Это действительно помогло. Теперь мне нужно выяснить, как заставить его говорить дни недели из предоставленного xml. - person smiller48; 18.07.2014
comment
@ smiller48 Предлагаю вам задать об этом отдельный вопрос, поскольку в XSLT 1.0 это действительно непросто сделать. - person michael.hor257k; 18.07.2014