3

I am parsing the below xml content using the XmlParser class in groovy.
The content of xml is as follows:

<root><element1 attribute1="value1">Text content of element1</element1></root> 

And trying to retrieve the text content of the first child node of root node, like this:

output.element1.text() 

where, output is the result after parsing the xml content using XmlParser.

Completed code snippet I am running is as follows:

def parser = new XmlParser() def xmlContent = '<root><element1 attribute1="value1">Text content of element1</element1></root>' def output = parser.parseText(xmlContent) script.echo(output.element1.text()) 

It works fine in my local and gives expected output of script.echo as 'Text content of element1'

However, when I executed this in Jenkins groovy pipeline job, I get the following:

groovy.lang.MissingPropertyException: No such field found: field groovy.util.Node element1 

I compared the versions of groovy and java with the version used in Jenkins. But it's the same version.

In my local:

  • Groovy version - 2.4.21
  • Java version - 11

In Jenkins:

  • Groovy version - 2.4.21
  • Java version - 11
  • Jenkins version - 2.375.1

Do you know what might be the reason for such behavior in Jenkins with XmlParser? How to overcome this?

2
  • Not sure if this is a CPS transformation problem. Can you try adding the @NonCPS decorator just above your function call? (see: jenkins.io/doc/book/pipeline/cps-method-mismatches) Commented Feb 3, 2023 at 12:46
  • I'm using @NonCPS decorator above that function call and getting same issue. Commented Feb 6, 2023 at 11:01

1 Answer 1

0

It seems the reason is Groovy Sandbox Mode. If you have enough privilege to run it beyond sandbox (uncheck it and get approved by admin) your script should work as expected.

If you want a workaround, this should fix the problem in sandbox mode:

echo(output.get("element1").text()) 

In general I would consider converting XML to JSON and using readJSON step if conversion is possible in your use case. This is to follow the rule to avoid approvals as much as possible (safety) and keep pipeline simple.

Sign up to request clarification or add additional context in comments.

2 Comments

Why you mentioned Groovy sandbox mode, what's the issue in sandbox? Also, I am using the shared library to enhance our multibranch pipeline.
I think shared library doesn't matter here. All groovy content is running in Groovy Sandbox Mode as far as I know. Doc about it here. I just pointed out in my answer, the functionality you are using related to XML parsing has some problem with Groovy Sandbox Mode. I also gave you the solutions. Did you try them ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.