Announcement

Collapse
No announcement yet.

Kombination von max() und count()

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Kombination von max() und count()

    Hallo zusammen,

    ich stehe momentan auf den Schlauch und bitte um Eure Mithilfe.

    Ich habe folgendes Beispiel-XML:

    HTML Code:
    <root>
    	<element attr="1">Value1</element>
    	<element attr="1">Value1</element>
    	<element attr="2">Value1</element>
    	<element attr="2">Value1</element>
    	<element attr="2">Value1</element>
    	<element attr="3">Value1</element>
    	<element attr="4">Value1</element>
    	<element attr="4">Value1</element>
    </root>
    Nun möchte ich ermitteln, wie oft die häufigste Attribut-Id vorkommt. Sprich in diesem Beispiel wäre es attr="1", welche drei mal vorkommt, deshalb hätte ich gerne einen Ausdruck der mir "3" liefert.

    Hat jemand eine Idee?

    Gruß Martin
    Zuletzt editiert von derMartin; 21.03.2011, 15:25.

  • #2
    Mit XQuery:
    Code:
    let $r := <root>
    	<element attr="1">Value1</element>
    	<element attr="1">Value1</element>
    	<element attr="2">Value1</element>
    	<element attr="2">Value1</element>
    	<element attr="2">Value1</element>
    	<element attr="3">Value1</element>
    	<element attr="4">Value1</element>
    	<element attr="4">Value1</element>
    </root>
    return max(
      for $id in distinct-values($r/element/@attr)
      return count($r/element[@attr = $id])
    )
    Beachte, dass dein Beispiel mit der Notation <element @attr="1">...</element> kein XML ist, "@" ist nicht als Attributname erlaubt.

    Comment


    • #3
      Dank dir.
      Funktioniert wunderbar - sogar in einem value-of im XSLT über SAXON.

      Das "@" ist mir da nur so reingerutscht, weil ich gedanklich noch bei meinem XSLT Zugriffen war.

      Vielen Dank noch einmal.

      Comment


      • #4
        Ach so, wenn es um XSLT 2.0 geht, dann kann man das auch per for-each-group lösen:
        Code:
        <xsl:stylesheet
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          exclude-result-prefixes="xsd"
          version="2.0">
          
          <xsl:template match="root">
            <xsl:variable name="counts" as="xsd:integer*">
              <xsl:for-each-group select="element" group-by="@attr">
                <xsl:value-of select="count(current-group())"/>
              </xsl:for-each-group>
            </xsl:variable>
            <xsl:value-of select="max($counts)"/>
          </xsl:template>
          
        </xsl:stylesheet>

        Comment

        Working...
        X