Moving from XML stylesheets to ruby can seem daunting, but actually it's fun!
- if, choose, when, otherwise
- Equals and Other Comparisons
- for-each()
- substring-after()
- substring-before()
- text()
if
<xsl:if test="condition">[your code here]</xsl:if>Ruby
if condition
[your code here]
end
# or if you want to live dangerously
[your code here] if conditionchoose, when, otherwise
<xsl:choose>
<xsl:when test="condition">...</xsl:when>
<xsl:when test="condition2">...</xsl:when>
<xsl:otherwise>...</xsl:otherwise>
</xsl:choose>Ruby
if condition1
...
elsif condition2
...
else
...
endLeave out elsif if you have no second condition
Common Ruby operators:
| Name | Ruby |
|---|---|
| Equal | == |
| Not equal | != |
| Less than, etc | <, <= |
| Greater than, etc | >, >= |
|
Ruby
<xsl:variable name="fish" select="//some_xpath/text()"/>
<xsl:if test="$fish = 'trout'">[some code]</xsl:if>fish = @xml.get_text("//some_xpath")
if fish == "trout"
[some code]
endGiven this xml snippet:
<people>
<author @role="primary">
<persName><lastName>Cather</lastName></persName>
</author>
<author @role="editor">
<persName><lastName>Somebody</lastName></persName>
</author>
</people><xsl:for-each select="//author">
<xsl:value-of select="persName/lastName"/>
<xsl:text> the </xsl:text>
<xsl:value-of select="@role">
<xsl:for-each>authors = @xml.xpath("//author")
authors.each do |author|
lastname = author.get_text("persName/lastName")
role = author["role"]
puts "#{lastname} the #{role}"
endsubstring-after("Something|like this", "|")
"Something|like this".split("|").lastNote: .last will work great if your string only separated into two pieces. If you split on something like spaces and you need one of the words from the middle, you will have to work harder to get it out.
Xpath:
substring-before(string, '[Willa Cather]')
Ruby
string.split([Willa Cather]).firstAlternatively, you can use regex
string.split(/regex goes here/).firstXpath
ele/text()
Ruby
ele.text