Arsench
Arsench

Reputation: 187

Clone or copy JAXB XML block

I need your help please. I’m generating an XML file using JAXB. The client request that I need to do is, when retrieving data (from data base) to set into JAXB objects I have to check one of the element values. For example:

<id>123</id>
<Code>X22</Code>
**<location>A1-2-3</location>**

If the location value is as the above I have to change it to A1, A2 and A3 and set to location attribute cloning the block like example below. First copy

<id>123</id>
<Code>X22</Code>
<location>A1</location>

Second copy

<id>123</id>
<Code>X22</Code>
**<location>A2</location>**

Third copy

<id>123</id>
<Code>X22</Code>
**<location>A3</location>**

And set it into the same XML. My problem is that I can copy the blocks, but when I’m changing the location value it changes in all blocks, as I’m a beginner so please, help me if you can.

Thanks in advance.

Upvotes: 1

Views: 682

Answers (1)

lexicore
lexicore

Reputation: 43671

Disclaimer: I'm the author of JAXB2-Basics which includes the JAXB2 Copyable Plugin.

You can use the Copyable Plugin to achieve this. This plugin ganarates nice clone and copy... methods which can be used to deep copy your JAXB structures.

This is how it works.

  • First you have to enable the -Xcopyable plugin in your build.
  • You'll also need to add a org.jvnet.jaxb2_commons:jaxb2-basics-runtime dependency.
  • Your generated classes will get the clone() and copyTo(...) methods.
  • The simples would be to use clone(), just clone the whole thing and change the values you need to change.
  • A more advanced approach would be writing a CopyStrategy and use myJaxbObject.copyTo(null, otherInstance, myCopyStrategy) to "copy into" the òtherInstance with that strategy. The strategy can decide which values to copy and do some basic transformation.

Upvotes: 3

Related Questions