1
\$\begingroup\$

supposed I have an XML like

<root>
  <topic>
    <name>foo</name>
  </topic>
  <subject>
    <name>foo</name>
  </subject>
  <subject>
    <name>bar</name>
  </subject>
</root>

I want to add attributes to all <name> tags if they are children of a <subject>, bot not if they are children of a <topic>. My current approach is:

// Select all names which are childs of a subject

val names: Seq[Node] = (xml \\ "subject" \\ "name").theSeq


  private class AddAttributes(foo: Seq[Node]) extends RewriteRule {
    override def transform(n: Node): Seq[Node] = {
      n match {
        case elem: Elem if foo.contains(elem) => elem.copy(attributes = new UnprefixedAttribute("role", "nrol:full", Null))
        case other => other
      }
    }
  }


new RuleTransformer(new AddAttributes(names))(prepXml)

While this works, I wonder if there is a more "scalatic" way of doing this?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.