ballerina-platform/ballerina-library

NPE when Converting Record to XML Using 'xmldata:toXml()'

Opened this issue · 2 comments

Description:
Consider the following code:

import ballerina/xmldata;
import ballerina/io;

type Response record {|
    string? status;
    int? value;
    boolean? isTrue;
|};

public function main() returns error? {
    Response response = {
        status: "success",
        value: 10,
        isTrue: ()
    };
    xml x = check xmldata:toXml(response);
    io:println(x);
}

When there is a () value in the record, this returns a NPE.

error: java.lang.NullPointerException {"message":"Cannot invoke "Object.getClass()" because "value" is null"}
        at ballerina.xmldata.2:getModifiedRecord(xmldata.bal:96)
           ballerina.xmldata.2:toXml(xmldata.bal:68)
           xmldata:main(xmldata.bal:16)

Bal version: 2201.8.6

We are not supporting nullable fields. We only support optional fields like below,

import ballerina/xmldata;
import ballerina/io;

type Response record {|
    string status?;
    int value?;
    boolean isTrue?;
|};

public function main() returns error? {
    Response response = {
        status: "success",
        value: 10,
        isTrue: ()
    };
    xml x = check xmldata:toXml(response);
    io:println(x);
}

This will remove the element completely when the value is nil or not set.

Referring to the SFO[1], we should support nillable fields by adding the attribute xsi:nil="true" to the nil fields

  1. https://stackoverflow.com/questions/774192/what-is-the-correct-way-to-represent-null-xml-elements