I am new to Groovy and am stuck with a simple problem. All I wanna do is extract certain elements from one XML file and created a new file with it. Here's an example XML, let's use a Maven pom file:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.group</groupId>
<artifactId>artifact</artifactId>
<version>1.4</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
I know how to parse XML in Groovy:
def project = new XmlParser().parse("pom.xml")
project.groupId.each{
println it.text()
}
I also know how to create XML in Groovy:
def xml = new groovy.xml.MarkupBuilder()
xml.project (){
modelVersion("artifactId")
groupId("com.group")
artifactId("artifact")
}
However, I seem to have a problem combining the two. I want, for example, take groupId, artifactId and the whole dependencies tree and create a new XML from it. It can't be that hard and I wanna make use of the Groovy simplicity.
Something along those lines (of course this does not work):
def newXml= new groovy.xml.MarkupBuilder()
newXml.groupId= project.groupId
newXml.dependencies = project.dependencyManagement.dependencies
Thanks. That code helped a lot but how can I handle the namespace, i.e. if the project tag in the input looks like that:
<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">
It is then adding some weird annotations to the output. All I want is that the project tag in the output looks like that as well.
You can do this with
XmlSlurper
:Which prints:
To handle the namespaces better, you could try:
Which should give you: