The logo is a pig framed between two angle brackets.

XProc 3.0 Tutorial

Conditional Expressions: <p:if/> and <p:choose/>

With conditional expressions you can decide under which conditions different function blocks are executed. Which computations are performed depends on whether a defined condition results in the values true or false. In XProc, there are two steps for conditional expressions:

  • p:if: the code is executed when the condition is met.
  • p:choose: you can express multiple condition branches with p:when and include a fallback with p:otherwise if none of the conditions are satisfied.

Conditionals With <p:if/>

Here is an example using p:if to literally filter out the needle in the haystack. The @test attribute contains an XPath that evaluates to true or false:

<?xml version="1.0" encoding="UTF-8"?>
<p:declare-step xmlns:p="http://www.w3.org/ns/xproc" version="3.0">
  <p:input port="source">
    <p:inline>
      <haystack>
        <hay/>
        <hay/>
        <needle/>
      </haystack>
    </p:inline>
  </p:input>
  
  <p:output port="result"/>
  
  <p:if test="/haystack/needle">
    
    <p:filter select="/haystack/needle"/>
    
  </p:if>
  
</p:declare-step>

Output

<xml version="1.0" encoding="UTF-8"?>
<needle/>

Conditionals With <p:choose/>

The next example shows a p:choose used to increase the speed of a cooling-fan depending on the given temperature. Please note that for temperatures greater than 100 degrees both conditions would be true. If multiple p:when branches match, the first matching p:when is selected.

<?xml version="1.0" encoding="UTF-8"?>
<p:declare-step xmlns:p="http://www.w3.org/ns/xproc" version="3.0">
  <p:input port="source">
    <p:inline>
      <pc>
        <temperature unit="celsius">96</temperature>
        <cooling-fan unit="rpm">3000</cooling-fan>
      </pc>
    </p:inline>
  </p:input>
  
  <p:output port="result"/>
  
  <p:choose>
    <p:when test="/pc/temperature > 100">
      <p:string-replace match="/pc/cooling-fan/text()" replace="5000"/>
    </p:when>
    <p:when test="/pc/temperature > 75">
      <p:string-replace match="/pc/cooling-fan/text()" replace="4000"/>
    </p:when>
    <p:otherwise>
      <p:identity/>
    </p:otherwise>
  </p:choose>
  
</p:declare-step>

Output

<xml version="1.0" encoding="UTF-8"?>
<pc>
  <temperature unit="celsius">96</temperature>
  <cooling-fan unit="rpm">4000</cooling-fan>
</pc>

Read more…