用scala以编程方式替换xml值

Jef*_*man 4 xml scala

我正在编写一个工具来使用scala更新一些xml文件(本例中为pom.xml),因为它在java中的工作量明显高于(理论上)scala.我可以很好地解析xml文件,但我需要替换现有xml中的节点并重写结果.例如:

<dependency>
    <groupId>foo</groupId>
    <artifactId>bar</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

所以我想找到这样的所有节点并将其替换为:

<dependency>
    <groupId>foo</groupId>
    <artifactId>bar</artifactId>
    <version>1.0</version> <!-- notice the lack of -SNAPSHOT here -->
</dependency>
Run Code Online (Sandbox Code Playgroud)

所以,我可以简单地获得所有版本节点,但是如何用我想要的节点替换它们?

// document is already defined as the head of the xml file
nodes = for (node <- document \\ "version"; if (node.text.contains("SNAPSHOT"))) yeild node
Run Code Online (Sandbox Code Playgroud)

那我想做点什么:

for (node <- nodes) {
    node.text = node.text.split("-")(0)
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为节点是不可变的.我查看了Node的复制方法,但它不包含text在参数中.

Dan*_*ral 12

您真的应该看一下有关修改XML的Stack Overflow的其他问题.查看右侧的"相关"链接.

这里:

scala> <dependency>
     |     <groupId>foo</groupId>
     |     <artifactId>bar</artifactId>
     |     <version>1.0-SNAPSHOT</version>
     | </dependency>
res0: scala.xml.Elem =
<dependency>
    <groupId>foo</groupId>
    <artifactId>bar</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

scala> new scala.xml.transform.RewriteRule {
     |   override def transform(n: Node): Seq[Node] = n match {
     |     case <version>{v}</version> if v.text contains "SNAPSHOT" => <version>{v.text.split("-")(0)}</version>
     |     case elem: Elem => elem copy (child = elem.child flatMap (this transform))
     |     case other => other
     |   }
     | } transform res0
res9: Seq[scala.xml.Node] =
<dependency>
    <groupId>foo</groupId>
    <artifactId>bar</artifactId>
    <version>1.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)