Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Adding a new node to an XML file in Groovy

Whilst working on a Grails plugin I needed to add an extra import statement to the Spring resources.xml config file, here's how I did it.


def parser= new XmlParser().parse(new File('resources.xml'))

if (!parser.'import'.'@resource'.contains('foo.xml')) {
def newNode = new Node(res, 'import', [resource: 'foo.xml'])
res.'import'.add(newNode)
}

def writer = new FileWriter('resources.xml')
new XmlNodePrinter(new PrintWriter(writer)).print(parser)

Using XStream in Java

Reading a file with XStream...
XStream stream = new XStream();
MyClass myClass = (MyClass)stream.fromXML(
new FileReader(fileName));

Writing a file with XStream
MyClass myClass = new myClass();
XStream stream = new XStream();
stream.toXML(myClass , System.out);