xsl代码不会返回所有城市

时间:2016-10-13 21:32:23

标签: xml xslt

xsl代码只为每个国家/地区返回一个城市。知道为什么吗?因为我期待得到每个国家的所有城市。

你可以看到我得到的代码和结果:

RESULT

<html>
   <ul>
      <li>United States</li>
      <li>LA</li>
      <li></li>
   </ul>
   <ul>
      <li>Poland</li>
      <li>Gdańsk</li>
      <li></li>
   </ul>
</html>

CODE

   <html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0">
    <xsl:for-each select="//nations">
        <xsl:for-each select="nation">
          <ul>
            <li><xsl:value-of select="nationame"/></li>
            <li><xsl:value-of select="cities/city/cityname"/></li>
            <li><xsl:value-of select="cities/city/population"/></li>
          </ul>
        </xsl:for-each>
    </xsl:for-each>
</html>

<nations>
  <nation>
    <nationame>United States</nationame>
    <cities>
      <city>
          <cityname>LA</cityname>
          <citypopulation>4000000</citypopulation>
      </city>
      <city>
          <cityname>NY</cityname>
          <citypopulation>10000000</citypopulation>
      </city>
    </cities>
  </nation>
  <nation>
    <nationame>Poland</nationame>
    <cities>
      <city>
          <cityname>Gdańsk</cityname>
          <citypopulation>40000</citypopulation>
      </city>
      <city>
          <cityname>Poznań</cityname>
          <citypopulation>100000</citypopulation>
      </city>
    </cities>
  </nation>
</nations>

有人意识到为什么不工作?

2 个答案:

答案 0 :(得分:1)

在XSLT 1.0中,xsl:value-of指令返回所选节点集中第一个节点的字符串值。要获取所有值,您需要使用(另一个)xsl:for-each,例如:

<html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0">
    <xsl:for-each select="nations/nation">
        <ul>
            <li><xsl:value-of select="nationame"/></li>
            <xsl:for-each select="cities/city">
                <li><xsl:value-of select="cityname"/></li>
            </xsl:for-each>
        </ul>
    </xsl:for-each>
</html>

答案 1 :(得分:0)

首先,您需要另一个for-each循环来遍历城市。否则,XSLT将匹配它找到的第一个城市

其次,您错误地调用了人口。您的XML具有citypopulation节点,而您的XSLT引用population

相关问题