【问题标题】:Jenkins - how to set an XML attribute and then write back to an XML fileJenkins - 如何设置 XML 属性然后写回 XML 文件
【发布时间】:2019-06-13 10:11:26
【问题描述】:

从我的last post here 开始,向我展示了如何读取 XML 属性,我现在的最后一个任务是设置属性,例如我将增加读取属性,然后回写。

所以,我又得到了以下 XML 文件:

 <?xml version='1.0' encoding='utf-8'?>
<widget android-versionCode="16" id="com.mycomp.myapp" ios-CFBundleVersion="15" version="1.3.0.b4" windows-packageVersion="1.2.6.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>My App</name>
    <description>My app description</description>
    <author>mycom.com.au</author>

根据帮助,我了解到以下内容不起作用:

def xml = readFile "${env.WORKSPACE}/config.xml"
def rootNode = new XmlParser().parseText(xml)
def version = rootNode.@version

但以下会:

def version = rootNode.attributes()['version']

我现在似乎在写回属性时遇到了同样的问题。

按照this post我尝试了以下设置属性:

 def filePath = "${env.WORKSPACE}/config.xml"
 def xml = readFile filePath
 def rootNode = new XmlParser().parseText(xml)         
 rootNode.@version = "12345"         
 def writer = new FileWriter(filePath)
 new XmlNodePrinter(new PrintWriter(writer)).print(rootNode)

但我在尝试读取属性时遇到了类似的错误:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: No such field found: field groovy.util.Node version
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:425)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onSetAttribute(SandboxInterceptor.java:447)
at org.kohsuke.groovy.sandbox.impl.Checker$9.call(Checker.java:405)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedSetAttribute(Checker.java:411)

我确实在 Groovy 操场上尝试过,它似乎确实有效,但在 Jenkins 中却不行。

因此,.@version 语法似乎再次不起作用,我无法找到替代调用(就像获取属性一样)来设置属性。

我该怎么做?

【问题讨论】:

  • 我还更新了您关于属性访问的其他问题。

标签: jenkins jenkins-pipeline jenkins-groovy


【解决方案1】:

经过更多测试,我发现,我们可以简单地在[] 访问中使用@ 选择器(编辑:它称为map notation),似乎脚本沙箱可以处理这个问题。它在 jenkins 允许被批准的引擎盖下翻译为 getAt()putAt()

node() {
    def xml = readFile "${env.WORKSPACE}/config.xml"
    def rootNode = new XmlParser().parseText(xml)
    print rootNode['@version']
    rootNode['@version'] = 123
    print rootNode['@version']
}

结果

Running on Jenkins in /var/jenkins_home/workspace/xmltest
[Pipeline] {
[Pipeline] readFile
[Pipeline] echo
1.3.0.b4
[Pipeline] echo
123
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

【讨论】:

  • 再次非常感谢您!以上工作100%!我会记下这些语法以备将来使用。
猜你喜欢
  • 1970-01-01
  • 2017-02-15
  • 2018-08-30
  • 2023-01-24
  • 2017-05-27
  • 2015-05-19
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
相关资源
最近更新 更多