Home > Software design >  How can I use JAXB to bind mulitple non-unique elements
How can I use JAXB to bind mulitple non-unique elements

Time:02-16

I'm having this issue with parsing XML using JAXB. Here is a simplified layout of the XML in question:

<message>
  <header>
    <network>NET</network>
    <sendTime>0722</sendTime>
  </header>
  <generalInformation>
    <senderReference>1234</senderReference>
    <linkage>
      <externalReference>extRef</externalReference>
    </linkage>
    <linkage>
      <internalReference>intRef</internalReference>
    </linkage>
    <linkage>
      <systemReference>sysRef</externalReference>
    </linkage>
  </generalInformation>
</message>

The problem I'm having is that these references are being sent under the linkage tag which is not unique, and also doesn't have a root like "linkages" which would allow me to easily wrap it in a list in Java, because the generalInformation tag has other tags in it. Here is how I have it set up so far:

@XmlRootElement(name="message")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Message {
  private Header header;
  private GeneralInformation generalInformation;
}

@XmlRootElement(name="header")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Header {
  private String network;
  private String sendTime;
}

@XmlRootElement(name="generalInformation")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class GeneralInformation {
  private String senderReference;
  //How to create for linkages??
}

So my question to you is, how can I configure the GeneralInformation class to handle these multiple linkages? I am mostly concerned with unmarshalling from XML to Java at the moment.

CodePudding user response:

Just define it as a List, for example:

private List<Linkage> linkage;

and define the Linkage class to have single String property:

@XmlRootElement(name="linkage")
...
public class Linkage {
  private String systemReference;
}

CodePudding user response:

@XmlRootElement(name="generalInformation")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class GeneralInformation {
  private String senderReference;
  private List<Linkage>;
}

@XmlRootElement(name="linkage")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Linkage {
  private String externalReference;
  private String internalReference;
  private String systemReference;
}
  • Related