创建不同xml项的列表并将它们计算为xpath v1.0

时间:2018-05-16 15:32:42

标签: xml xslt xpath

我正在使用xslt xpath v1.0和以下xml:

<store>
<item>
    <title>tshirt</titlet>
</item>
<item>
    <title>shoes</titlet>
</item>
<item>
    <title>boots</titlet>
</item>
<item>
    <title>boots</titlet>
</item>
<item>
    <title>shoes</titlet>
</item>
<item>
    <title>boots</titlet>
</item>
</store>

输出应该是降序列表,如:

项目名称(xml中的总项目)

boots(3)

鞋子(2)

tshirt(1)

我找到了一种识别它们的方法,但找不到计算方法

<xsl:for-each select="item[not(preceding::item/. = .)]">
            <xsl:value-of select="." />
</xsl:for-each>

2 个答案:

答案 0 :(得分:3)

使用纯XPath 1很困难但是当你使用XSLT时,你可以使用Muenchian grouping进行分组并xsl:sort进行排序:

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

  <xsl:output method="html" indent="yes" version="5" doctype-system="about:legacy-doctype"/>

  <xsl:key name="group" match="item" use="title"/>

  <xsl:template match="/">
    <html>
      <head>
        <title>.NET XSLT Fiddle Example</title>
      </head>
      <body>
          <ul>
              <xsl:apply-templates select="store/item[generate-id() = generate-id(key('group', title)[1])]">
                  <xsl:sort select="count(key('group', title))" order="descending" data-type="number"/>
              </xsl:apply-templates>
          </ul>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="item">
      <li>
          <xsl:value-of select="concat(title, ' (', count(key('group', title)), ')')"/>
      </li>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/nc4NzQb

答案 1 :(得分:0)

您可以使用此:

  <xsl:variable name="FullXml" select="/store"/>
  <xsl:for-each select="distinct-values(/store/item/title/text())">
      <xsl:variable name="TheContent" select="." />
      <xsl:value-of select="$TheContent"/>(<xsl:value-of select="count($FullXml/item[title/text()=$TheContent])" />)
  </xsl:for-each>

使用distinct-values(),您将获得所有值的列表,并使用.count()找到他们的号码。