Note that there are some explanatory texts on larger screens.

plurals
  1. POGroovy: copy XML elements from one doc to another
    text
    copied!<p>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:</p> <pre><code>&lt;project&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.group&lt;/groupId&gt; &lt;artifactId&gt;artifact&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;dependencyManagement&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;4.8.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/dependencyManagement&gt; </code></pre> <p></p> <p>I know how to parse XML in Groovy:</p> <pre><code>def project = new XmlParser().parse("pom.xml") project.groupId.each{ println it.text() } </code></pre> <p>I also know how to create XML in Groovy:</p> <pre><code>def xml = new groovy.xml.MarkupBuilder() xml.project (){ modelVersion("artifactId") groupId("com.group") artifactId("artifact") } </code></pre> <p>However, I seem to have a problem combining the two. I want, for example, take <em>groupId</em>, <em>artifactId</em> and the whole <em>dependencies</em> tree and create a new XML from it. It can't be that hard and I wanna make use of the Groovy simplicity.</p> <p>Something along those lines (of course this does not work):</p> <pre><code>def newXml= new groovy.xml.MarkupBuilder() newXml.groupId= project.groupId newXml.dependencies = project.dependencyManagement.dependencies </code></pre> <hr> <p>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:</p> <pre><code>&lt;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"&gt; </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload