preserve formatting when updating xml file with groovy

后端 未结 2 370
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:35

    I just created gist at: https://gist.github.com/akhikhl/8070808 to demonstrate how such transformation is done with Groovy and JDOM2.

    Important notes:

    1. Groovy technically allows using any java libraries. If something cannot be done with Groovy JDK, it can be done with other library.
    2. jaxen library (implementing XPath) should be included explicitly (via @Grab or via maven/gradle), since it's an optional dependency of JDOM2.
    3. The sequence of @Grab/@GrabExclude instructions fixes the quirky dependence of jaxen on JDOM-1.0.
    4. XPathFactory.compile also supports variable binding and filters (see online javadoc).
    5. XPathExpression (which is returned by compile) supports two major functions - evaluate and evaluateFirst. evaluate always returns a list of all XML-nodes, satisfying the specified predicate, while evaluateFirst returns just the first matching XML-node.

    Update

    The following code:

    new XMLOutputter().with {
      format = Format.getRawFormat()
      format.setLineSeparator(LineSeparator.NONE)
      output(doc, System.out)
    }
    

    solves a problem with preserving whitespaces and line separators. getRawFormat constructs a format object that preserves whitespaces. LineSeparator.NONE instructs format object, that it should not convert line separators.

    The gist mentioned above contains this new code as well.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题