title: Transforming an XML element based on its sibling, using scala.xml.transform.RuleTransformer
body: <p>Given this XML: </p>
  
  <pre><code>&lt;root&gt;
   &lt;item&gt;
     &lt;discriminator&gt;d1&lt;/discriminator&gt;
     &lt;target&gt;t1&lt;/target&gt;
     &lt;subitem&gt;
         &lt;incomplete&gt;&lt;/incomplete&gt;
     &lt;/subitem&gt;
     &lt;subitem&gt;
         &lt;incomplete&gt;&lt;/incomplete&gt;
     &lt;/subitem&gt;
   &lt;/item&gt;
   &lt;item&gt;
      &lt;discriminator&gt;d2&lt;/discriminator&gt;
     &lt;target&gt;t2&lt;/target&gt;
     &lt;subitem&gt;
         &lt;incomplete&gt;&lt;/incomplete&gt;
     &lt;/subitem&gt;
   &lt;/item&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>I need to transform it such that: <br>
  1) for each <code>&lt;item&gt;</code>, text of <code>&lt;target&gt;</code> is modified  based on the text in <code>&lt;discriminator&gt;</code>. <br> 
  2) for each <code>&lt;incomplete&gt;</code>, add some text content. </p>
  
  <p>Based on other SO posts, so far I've come up with a solution for 2), using <code>RewriteRule</code> and <code>RuleTransformer</code>. It goes like this: </p>
  
  <pre><code>object completeIncomplete extends RewriteRule {
        override def transform(n: Node): Seq[Node] = n match {
          case Elem(_, "incomplete", _, _, _*) =&gt;
            &lt;incomplete&gt;content&lt;/incomplete&gt;
          case other =&gt; other
        }
      }
  object transform extends RuleTransformer(completeIncomplete)
  transform(xml)
  </code></pre>
  
  <p>This seems to work fine, but I don't know: </p>
  
  <ul>
  <li>how to achieve 1) (modifying an element based on its sibling)</li>
  <li>how to combine the two processing steps. That is: does it make sense in this case to have two different RewriteRule-s? Is that two wasteful? Is it possible/advisable to achieve both transformations in a single iteration? <br></li>
  </ul>
  
  <p>For 1), I have tried to pattern match the list of children, like this: <br></p>
  
  <pre><code>case Elem("", "item", _, _, disc@Elem("", "discriminator", _, _, _*)) 
      if discriminate(disc) =&gt; //...?
  </code></pre>
  
  <p>or this:</p>
  
  <pre><code>case item@Elem("", "item", _, _, _*) 
      if discriminate(item \ "disc") =&gt; //..?
  </code></pre>
  
  <p>But that didn't work out so well, because I don't know how to recreate the whole item with only replacing <code>&lt;target&gt;</code></p>
  
  <p>I don't even know if in this case matching against <code>&lt;item&gt;</code> is the way to go. But if it is, can I somehow achieve the transformation of its <code>&lt;incomplete&gt;</code>children? </p>
  
  <p>What is the correct approach here? </p>