Last active
November 13, 2015 23:59
-
-
Save fancellu/439ebc71da9cc9bde45a to your computer and use it in GitHub Desktop.
RewriteRuleExample for Scala XML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<document> | |
<people><person name="John" id="john"/><person name="Mary" id="mary"/></people> | |
<text>Hello <a href="john">John</a>, say hi to <a href="mary">Mary</a></text> | |
</document> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.xml._ | |
import scala.xml.transform._ | |
object RewriteRuleExample extends App { | |
val xml = | |
<document> | |
<people><person name="John" id="john"/><person name="Mary" id="mary"/></people> | |
<text>Hello John, say hi to Mary</text> | |
</document> | |
val persons = xml \\ "person" | |
def doReplace(textIn: Node) = { | |
var text = textIn.text | |
for { | |
person <- persons | |
name = person \ "@name" | |
id = person \ "@id" | |
} text = text.replace(name text, <a href={id}>{name}</a> toString) | |
Unparsed(text) | |
} | |
object Handle extends RewriteRule { | |
override def transform(n: Node) = n match { | |
case text @ <text>{x}</text> => text.asInstanceOf[Elem].copy(child=doReplace(x)) | |
case _ => n | |
} | |
} | |
println(new RuleTransformer(Handle)(xml)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment