我有大量包含URL的XML文件.我正在编写一个groovy实用程序来查找每个URL并将其替换为更新版本.
给定example.xml:
<?xml version="1.0" encoding="UTF-8"?>
<page>
<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>
Run Code Online (Sandbox Code Playgroud)
脚本运行后,example.xml应包含:
<?xml version="1.0" encoding="UTF-8"?>
<page>
<content>
<section>
<link>
<url>/a/new/and/improved/url</url>
</link>
<link>
<url>/a/new/and/improved/url</url>
</link>
</section>
<section>
<link>
<url>
/a/different/new/and/improved/url?with=specialChars&stillEscaped=true
</url>
</link>
</section>
</content>
</page>
Run Code Online (Sandbox Code Playgroud)
这很容易使用groovy的优秀xml支持,除了我想要更改URL而不是文件的其他内容.
我的意思是:
到目前为止,在尝试了XmlParser,DOMBuilder,XmlNodePrinter,XmlUtil.serialize()等的许多组合之后,我已经逐行阅读每个文件,并应用了xml实用程序和正则表达式的丑陋混合.
读写每个文件:
files.each { File file ->
def lineEnding = file.text.contains('\r\n') ? '\r\n' : '\n'
def newLineAtEof = file.text.endsWith(lineEnding)
def lines = …Run Code Online (Sandbox Code Playgroud)