问题描述
我正在编写一个工具来使用 scala 更新一些 xml 文件(在这种情况下为 pom.xml),因为它在 java 中的工作量明显高于(理论上)它在 scala 中的工作量.我可以很好地解析xml文件,但是我需要替换现有xml中的节点并重写结果.例如:
I'm writing a tool to update some xml files (pom.xml in this case) with scala because the effort it would take in java is significantly higher than (in theory) it is with scala. I can parse the xml file just fine, but I need to replace nodes in the existing xml and rewrite the result. for example:
<dependency>
<groupId>foo</groupId>
<artifactId>bar</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
所以我想找到所有这样的节点并将它们替换为:
So I want to find all nodes like this and replace them with:
<dependency>
<groupId>foo</groupId>
<artifactId>bar</artifactId>
<version>1.0</version> <!-- notice the lack of -SNAPSHOT here -->
</dependency>
所以,我可以简单地获取所有版本节点,但是如何将它们替换为我想要的节点呢?
So, I can get all the version nodes simply enough, but how to replace them with the node that I want?
// document is already defined as the head of the xml file
nodes = for (node <- document \\ "version"; if (node.text.contains("SNAPSHOT"))) yeild node
然后我想做类似的事情:
then I want to do something like:
for (node <- nodes) {
node.text = node.text.split("-")(0)
}
这不起作用,因为节点是不可变的.我查看了 Node 的 copy 方法,但它不包含 text
作为参数.
which doesn't work because node is immutable. I looked at the copy method for a Node, but it doesn't include text
as a parameter.
推荐答案
你真的应该看看 Stack Overflow 上关于修改 XML 的其他问题.查看右侧的相关"链接.
You really should take a look at other questions on Stack Overflow about modifying XML. Look at the "Related" links to the right.
这里:
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>
这篇关于用scala以编程方式替换xml值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!