preserve formatting when updating xml file with groovy

后端 未结 2 374
Happy的楠姐
Happy的楠姐 2020-12-31 06:48

I have a large number of XML files that contain URLs. I\'m writing a groovy utility to find each URL and replace it with an updated version.

Given example.xml:

2条回答
  •  死守一世寂寞
    2020-12-31 07:45

    There is a solution without any 3rd party library.

    def xml = file.text
    def document = groovy.xml.DOMBuilder.parse(new StringReader(xml))
    def root = document.documentElement
    use(groovy.xml.dom.DOMCategory) {
        // manipulate the XML here, i.e. root.someElement?.each { it.value = 'new value'}
    }
    
    def result = groovy.xml.dom.DOMUtil.serialize(root)
    
    file.withWriter { w ->
        w.write(result)
    }
    

    Taken from http://jonathan-whywecanthavenicethings.blogspot.de/2011/07/keep-your-hands-off-of-my-whitespace.html

提交回复
热议问题