2

I have an XML string where some nodes have text between the tags, like so:

<note>
<to>Text between tags</to>
<from>More text</from>
<empty />
</note>

In Scala, how can I remove the text between these tags so that I get a string like this?:

<note><to></to><from></from><empty /></note>

1 Answer 1

2

You can use a RewriteRule for this and set Text nodes to Empty e.g.

val removeText = new RewriteRule {
  override def transform(n: Node): NodeSeq = n match  {
    case e: Text => NodeSeq.Empty
    case _ => n
  }
}

Then you can use RuleTransformer to transform your XML e.g.

  val source = scala.io.Source.fromFile("myData.xml")
  val lines = try source.mkString finally source.close()
  val xml = XML.loadString(lines)
  val output = new RuleTransformer(removeText).transform(xml)
  println(output)

Output: <note><to/><from/><empty/></note>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.