相关疑难解决方法(0)

使用groovy更新xml文件时保留格式

我有大量包含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&amp;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&amp;stillEscaped=true
                </url>
            </link>
        </section>
    </content>
</page>
Run Code Online (Sandbox Code Playgroud)

这很容易使用groovy的优秀xml支持,除了我想要更改URL而不是文件的其他内容.

我的意思是:

  • 空格不得更改(文件可能包含空格,制表符或两者)
  • 必须保留评论
  • 必须保留windows与unix样式的行分隔符
  • 不得添加或删除顶部的xml声明
  • 标签中的属性必须保留其顺序

到目前为止,在尝试了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)

regex xml groovy

13
推荐指数
2
解决办法
6083
查看次数

标签 统计

groovy ×1

regex ×1

xml ×1