0

我是 Groovy 的新手,不知何故在语法上苦苦挣扎。我有一个 NodeChildren 类型的对象(在 groovy.util.slurpersupport 中),它表示这样的 XML 结构:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.camerontec.catalys.node</groupId>
  <artifactId>catalys-node-core</artifactId>
  <version>2.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.4</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>

我想做的只是为其添加另一个依赖项,例如:

<dependency>
  <groupId>jdom</groupId>
  <artifactId>jdom</artifactId>
  <version>1.1.1</version>
  <scope>compile</scope>
</dependency>

我必须相当简单,但由于某种原因我无法弄清楚。任何帮助表示赞赏。

4

1 回答 1

0

您可以使用 XmlSlurper 来做到这一点(如果您关闭命名空间,因此 XmlSlurper 不会在所有非命名空间标记前加上tag0) - 我删除了 2 个原始部门以节省此答案的空间

import groovy.xml.*

def original = '''<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.camerontec.catalys.node</groupId>
  <artifactId>catalys-node-core</artifactId>
  <version>2.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>'''

def newDep = '''<dependency>
  <groupId>jdom</groupId>
  <artifactId>jdom</artifactId>
  <version>1.1.1</version>
  <scope>compile</scope>
</dependency>'''

def newNode = new XmlSlurper().parseText( newDep )
def oldNode = new XmlSlurper( false, false ).parseText( original )

oldNode.dependencies.appendNode( newNode )
String xmlStr = XmlUtil.serialize( new StreamingMarkupBuilder().bind { mkp.yield oldNode } )
println xmlStr
于 2013-04-11T09:01:36.053 回答