0

I will be receiving the following XML data in a variable.

<order>
   <name>xyz</name>
   <city>abc</city>
   <string>aGVsbG8gd29ybGQgMQ==</string>
   <string>aGVsbG8gd29ybGQgMg==</string>
   <string>aGVsbG8gd29ybGQgMw==</string>
 </order>

Output:

 <order>
       <name>xyz</name>
        <city>abc</city>
       <string>hello world 1</string>
       <string>hello world 2</string>
       <string>hello world 3</string>
 </order>

I know how I can decode from base64 but the problem is some of the values are decoded already and some are encoded. What is the best approach to decode this data using groovy so that I get the output as shown?

Always: tag value will be encoded. rest all other tags and value will be decoded.

user3384231
  • 3,641
  • 2
  • 18
  • 27
  • do you know which tags' content would be always encoded & which are not? – Yuri G Nov 08 '19 at 16:25
  • @YuriG yes. Always: tag value will be encoded. I can have multiple tags. It could be atleast 60,000 tags which would be encoded. No other tag will be encoded. – user3384231 Nov 08 '19 at 16:30
  • Then I don't see what is your issue here? Just traverse the XML, get all elements, decode them, put them back. Convert back into String if needed. That's it. – Yuri G Nov 08 '19 at 16:34
  • sorry, new to groovy. do you have any example that I can see? @YuriG – user3384231 Nov 08 '19 at 16:36
  • Possible duplicate of [XmlSlurper: How to change the text of a dynamic node](https://stackoverflow.com/questions/16061762/xmlslurper-how-to-change-the-text-of-a-dynamic-node) – cfrick Nov 08 '19 at 18:40

1 Answers1

0

Since there's no uncertainty on which nodes could come encoded and which not, hence no need to detect base64 encoding, the way to do it is pretty simple:

  1. Parse it. There's two preferable ways to do that in Groovy: XmlSlurper & XmlParser. They differ in computation & mem consumption modes, both provide object/structure representation in the end, though.
  2. Work with that object structure: traverse all required elements, decode the content/attributes you need to decode.
  3. Either proceed further with the data with them and/or serialize it back to the XML text.

Articles to look at:

Load, modify, and write an XML document in Groovy

https://www.baeldung.com/groovy-xml

https://groovy-lang.org/processing-xml.html

and many, many more.

Another cheat sheet always useful for Groovy noobs: http://groovy-lang.org/groovy-dev-kit.html

Check out how to traverse the structures there, for instance.

Yuri G
  • 1,206
  • 1
  • 9
  • 13
  • Thanks. I will go through your links. I was stuck in some other project so didn't get a chance to look into it yet. – user3384231 Nov 24 '19 at 18:15