0

I am new to XSLT so excuse me if this is a noob question.

Let's say I have this XML document (one hotel element with 2 private_rates):

<hotel>
  <private_rates>
    <private_rate>
      <id>1</id>
    </private_rate>
    <private_rate>
      <id>2</id>
    </private_rate>
  </private_rates>
</hotel>

Is there any way to use XSLT to transform it into 2 hotel elements, each with one private rate ?

<hotel>
  <private_rates>
    <private_rate>
      <id>1</id>
    </private_rate>
  </private_rates>
</hotel>
<hotel>
  <private_rates>
    <private_rate>
      <id>2</id>
    </private_rate>
  </private_rates>
</hotel>

How would the XSLT for that look like? Any help will be greatly appreciated! thanks.

basharaj
  • 76
  • 3
  • `I am new to XSLT so excuse me if this is a noob question.` that doesn't matter as far as you provide us what have you tried on your end. Right or wrong, without trying something its not fair to ask others to help. Happy SO.. :) – Rookie Programmer Aravind Mar 13 '13 at 08:31

2 Answers2

2

As an alternative to Jollymorphic's solution, my preference would be

<xsl:template match="private_rates">
      <hotel>
         <xsl:copy-of select="."/>
      </hotel>
</xsl:template>
Michael Kay
  • 156,231
  • 11
  • 92
  • 164
0

Since a legal XML document has to have a single, containing document element, I presume that this sequence of hotels is going inside something. That being said, how about this:

<xsl:template match="hotel">
   <xsl:for-each select="private_rates/private_rate">
      <hotel>
         <private_rates>
            <xsl:copy>
               <xsl:apply-templates />
            </xsl:copy>
         </private_rates>
      </hotel>
   </xsl:for-each>
</xsl:template>

The apply-templates usage here presumes that you also have an identity template in your stylesheet that will copy source content that isn't more specifically matched by other templates (such as this one).

Underscores are frowned upon in element and attribute names, incidentally.

Jollymorphic
  • 3,510
  • 16
  • 16
  • 1
    I don't know who frowns upon the underscores. I don't. – Michael Kay Mar 13 '13 at 08:15
  • @jollymorphic, `Underscores are frowned upon in element and attribute names, incidentally.` I don't see that as a valid point, can you pls explain?? – Rookie Programmer Aravind Mar 13 '13 at 08:27
  • @Others: It's just an aside, and purely a matter of taste. I should have said something more along the lines of "some people, myself included, frown on them because they needlessly translate the constraints of identifier names in programming languages into XML, which is a different world." There's another StackOverflow question on the subject of XML naming conventions that's probably worth browsing (and in which nobody suggests the use of underscores): http://stackoverflow.com/questions/1074447/case-conventions-on-element-names – Jollymorphic Mar 13 '13 at 13:53