Technogix
Technogix

Reputation: 77

Groovy : Reading xml from a file and adding node to it

I have a XML file say abc.xml at location (C:/Users/abc.xml), I want to update it by adding one module dependency.

abc.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ This is free software; you can redistribute it and/or modify it
  ~ under the terms of the GNU Lesser General Public License as
  ~ published by the Free Software Foundation; either version 2.1 of
  ~ the License, or (at your option) any later version.
  -->

<module xmlns="urn:jboss:module:1.3" name="org.picketbox">
    <!-- This module is deprecated and subject to being removed in a subsequent release. -->
    <properties>
      <property name="jboss.api" value="deprecated"/>
    </properties>

    <resources>
        <resource-root path="picketbox-4.9.6.Final.jar"/>
        <resource-root path="picketbox-infinispan-4.9.6.Final.jar"/>
        <resource-root path="picketbox-commons-1.0.0.final.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="javax.persistence.api" optional="true"/>
    </dependencies>
</module>

I tried to add module name="javax.xyz" at dependencies section by below code

def fileLocation = "C:/Users/abc.xml"
def abcXML = new XmlSlurper().parse(new File(fileLocation))
abcXML.dependencies.appendNode {
     module {
         name 'javax.xyz'
     }
}
XmlUtil.serialize(abcXML); 

This is not working without any error, the same code is working for simple xml(without any comment and only one node) file.

Upvotes: 0

Views: 1184

Answers (1)

Boaz
Boaz

Reputation: 4669

Try this

import groovy.xml.QName
import groovy.xml.XmlUtil

def xml = new File("C:/Users/abc.xml").text
def parser = new XmlParser()
def root = parser.parseText(xml)
def numberOfResults = parser.createNode(root.dependencies[0], new QName("module"), ["name":"javax.xyz"])
println XmlUtil.serialize(root)

You can refer to the documentation here http://groovy-lang.org/processing-xml.html#_adding_nodes

Upvotes: 1

Related Questions