如何从 Scala 中的 XML 字符串中去除文本? [英] How to strip text from XML string in Scala?

查看:53
本文介绍了如何从 Scala 中的 XML 字符串中去除文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 字符串,其中一些节点在标签之间有文本,如下所示:

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>

在 Scala 中,如何删除这些标签之间的文本,以便得到这样的字符串?:

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>

推荐答案

您可以使用 RewriteRule 并将文本节点设置为空,例如

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
  }
}

然后就可以使用RuleTransformer 转换您的 XML,例如

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)

输出:

这篇关于如何从 Scala 中的 XML 字符串中去除文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆