Serialize RecordList to and from XML

Updated: Oct 30, 2023

This example shows how to convert a RecordList to XML and back. You can use this functionality for data interchange between systems, configuration file management, and web services where XML is commonly used.

 

Java Code Listing

package com.northconcepts.datapipeline.examples.cookbook;

import com.northconcepts.datapipeline.core.Record;
import com.northconcepts.datapipeline.core.RecordList;

import java.io.IOException;
import java.math.BigInteger;

public class SerializeRecordListToFromXml {
    public static void main(String[] args) throws IOException {
        Record record1 = new Record();
        record1.setField("name", "John Wayne");
        record1.setField("balance", new BigInteger("1234567894"));

        Record record2 = new Record();
        record2.setField("name", "Peter Parker");
        record2.setField("balance", new BigInteger("9876543210"));

        RecordList recordList = new RecordList(record1, record2);

        String xml = recordList.toRecord().toXml();
        System.out.println("Serialization of record list to XML completed");
        System.out.println(xml);

        Record record = Record.fromXml(xml);
        Record document = record.getFieldValueAsRecord("document", new Record());
        RecordList recordList1 = new RecordList();
        recordList1.fromRecord(document);
        System.out.println("\nDeserialization of record list from XML completed");
        System.out.println(recordList1);
    }
}

 

Code Walkthrough

  1. First, two Record instances are created to store fields as a key-value pair.
  2. record1.setField() creates a field with the name specified in the first parameter and the value specified in the specified second parameter.
  3. RecordList is created to store the two records created in the previous steps.
  4. RecordList instance is first converted to a single Record instance and then XML-formatted string using toXml() method. The output is printed on the console.
  5. When serializing back from XML to RecordList, again single Record instance is created. 
  6. The RecordList instance is restored back from document record using fromRecord() method.

 

Console output

Serialization of record list to XML completed
<?xml version='1.0' encoding='UTF-8'?>
<document>
<records>
<name>John Wayne</name><balance>1234567894</balance>
</records>
<records>
<name>Peter Parker</name><balance>9876543210</balance>
</records>
</document> Deserialization of record list from XML completed RecordList [records=[ Record (MODIFIED) (is child record) { 0:[name]:STRING=[John Wayne]:String 1:[balance]:STRING=[1234567894]:String }, Record (MODIFIED) (is child record) { 0:[name]:STRING=[Peter Parker]:String 1:[balance]:STRING=[9876543210]:String }]]
Mobile Analytics