简体   繁体   中英

XSLT Count nodes of specific type

I have an xml and I want to count the price of all properties who have the type of apartment and average them. How do i go about doing that? I have tried using my way but it isn't working. As for the total properties with cheap rental price, how do i calculate it so that I can get the sum of all prices less than 400.

<p>Total number of properties : <xsl:value-of select="count(property/type[normalize-space(text())='apartment'])"/></p>
<p>Average price : <xsl:value-of select="count(property/type[normalize-space(text())='apartment']/price)"/></p>
<p>Total properties with cheap rental price : </p>

<rentalProperties>
  <property contact="0499584010">
    <type>house</type>
    <price>430</price>
    <address>
      <streetNo>111</streetNo> 
      <street>say, Burwood Road</street>
      <suburb>say, Hawthorn</suburb> 
      <state>VIC</state> 
      <zipcode>3122</zipcode>
    </address>
    <numberOfBedrooms>3</numberOfBedrooms>
    <numberOfBathrooms>1</numberOfBathrooms>
    <garage>1</garage>
    <description></description> 
  </property>
</rentalProperties>

I am rather confused regarding what exactly you want as the result. See if this can help:

<xsl:template match="/rentalProperties">
    <xsl:variable name="apartments" select="property[normalize-space(type)='apartment']" />
    <div>
        <p>Total number of apartments: <xsl:value-of select="count($apartments)"/></p>
        <p>Average apartment price: <xsl:value-of select="sum($apartments/price) div count($apartments)"/></p>
        <p>Total properties with cheap rental price: <xsl:value-of select="count(property[price &lt; 400])"/></p>
    </div>
</xsl:template>

Given the following example input:

<rentalProperties>
  <property contact="123">
    <type>apartment</type>
    <price>475</price>
  </property>
  <property contact="456">
    <type>house</type>
    <price>350</price>
  </property>
  <property contact="78">
    <type>apartment</type>
    <price>375</price>
  </property>
</rentalProperties>

the result will be:

<div>
  <p>Total number of apartments: 2</p>
  <p>Average apartment price: 425</p>
  <p>Total properties with cheap rental price: 2</p>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM