2013-04-11 82 views
0

我是Groovy的新手,不知何故在語法上掙扎。我有類型NodeChildren(在groovy.util.slurpersupport),其代表一個XML結構類似的目的:Groovy:將節點添加到NodeChildren

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

我一定很簡單,但由於某種原因,我無法弄清楚。任何幫助讚賞。

回答

0

你可以用的XmlSlurper做到這一點(如果你關掉命名空間等等的XmlSlurper不tag0前綴的所有非命名空間標籤) - 我去掉了原DEPS 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