Skip to content

Instantly share code, notes, and snippets.

@akhikhl
Last active July 17, 2021 08:16
Show Gist options
  • Save akhikhl/8070808 to your computer and use it in GitHub Desktop.
Save akhikhl/8070808 to your computer and use it in GitHub Desktop.
XML transformation with Groovy, JDOM2 and XPath
/*
* Copyright 2013 (c) Andrey Hihlovskiy
* License: MIT (http://opensource.org/licenses/MIT)
*/
@Grab('org.jdom:jdom2:2.0.5')
@Grab('jaxen:jaxen:1.1.4')
@GrabExclude('jdom:jdom')
import org.jdom2.*
import org.jdom2.input.*
import org.jdom2.xpath.*
import org.jdom2.output.*
def xml = '''<?xml version="1.0" encoding="UTF-8"?>
<page>
<!-- test comment -->
<content>
<section>
<link>
<url>/some/old/url</url>
</link>
<link>
<url>/some/old/url</url>
</link>
</section>
<section>
<link>
<url>
/a/different/old/url?with=specialChars&amp;escaped=true
</url>
</link>
</section>
</content>
</page>'''
Document doc = new SAXBuilder().build(new StringReader(xml))
def urls = XPathFactory.instance().compile('//url').evaluate(doc)
for(def url in urls) {
url.text = url.text.replaceAll($//some/old/url/$, '/a/new/and/improved/url')
url.text = url.text.replaceAll($//a/different/old/url/$, '/a/different/new/and/improved/url')
}
new XMLOutputter().with {
format = Format.getRawFormat()
format.setLineSeparator(LineSeparator.NONE)
// XmlOutputter can write to OutputStream or Writer, which is sufficient for most cases
output(doc, System.out)
}
@akhikhl
Copy link
Author

akhikhl commented Dec 21, 2013

To try this code, start groovyConsole, copy/paste code into it and invoke "Run" command.
Or, if you prefer command line:

  1. save the code to the file like "jdom2_transform.groovy".
  2. invoke "groovy jdom2_transform.groovy"

@ChipNowacek
Copy link

Run from command line (option 2 above), it's all good. Doesn't work in the shell. Any idea why I would get this?

groovy:000> . https://gist.githubusercontent.com/akhikhl/8070808/raw/77717147ada5c424c7e8bf99373f56a243d3075b/jdom2_transform.groovy
groovysh_evaluate: 1: unexpected token: * @ line 1, column 11.
org.jdom2.*
^

groovy:003> :=
Preferences:
interpreterMode=true
groovy:003>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment