Sunday, 24 January 2016

XML : JAXB unmarshalling - element that appears multiple times separated by other elements

I am trying to use JAXB to unmarshal an XML file that has an element that occurs 5 times, but not in a row; I want to make some changes, then marshal it back to XML. When written back to the XML file, the instances of the element need to go back in the same order, and be separated by the same intervening elements as before

I know I can represent an element that occurs multiple times with a Collection, and I can specify the order of fields using @XmlType( propOrder = { ... } ), but I can't figure out to do both at the same time...

I tried using 5 different field names in my Java class (encryptedData1, encryptedData2, ...), and 5 different pairs of getters/setters, and then annotating the setters with the same name:

  @XmlElement( name = "EncryptedData" )    

but when I unmarshal, only the first one gets set, the others are all null. The field that does get filled has the value of the last instance in the XML file, so I'm guessing it's just getting set five times

If I use a List, then when I write out to the XML file, they all get written together

Here is a sample of the original XML; the EncryptedData element is the one in question:

  <NodeInformation>  ...    <ProxyIpPort>1194</ProxyIpPort>    <LicenseKeyID />    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />      <CipherData>        <CipherValue>************************</CipherValue>      </CipherData>    </EncryptedData>    <ProxyUsername />    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />      <CipherData>        <CipherValue>***********************</CipherValue>      </CipherData>    </EncryptedData>    <ActualIpAddress />    <HasMASServer>false</HasMASServer>    <MASServerIpAddress />    <MASServerWebListeningPort>443</MASServerWebListeningPort>    <ModemNumber />    <RememberLoginPassword>true</RememberLoginPassword>    <LoginName>admin</LoginName>    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />      <CipherData>        <CipherValue>***************************</CipherValue>      </CipherData>    </EncryptedData>    ...  </NodeInformation>    

Thank you in advance for any insight

No comments:

Post a Comment