Last active
July 17, 2021 08:16
-
-
Save akhikhl/8070808 to your computer and use it in GitHub Desktop.
XML transformation with Groovy, JDOM2 and XPath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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&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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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>