Quick Tip: Fixing “Could not convert variant of type (Null) into type…”
I often use the XML Data Binding wizard in Delphi. However, it doesn’t seem to have been given a lot of attention from Borland/Inprise/Borland/CodeGear/Embarcadero/Idera. And unfortunately, out of the box what it generates is often error prone, apparently not supporting optional elements/attributes.
When the generated code tries to read an optional element or attribute, you will get a “Could not convert variant of type (Null) into type” exception.
The offending code usually looks like this:
function TXMLMyType.Get_OptionalElement: Single;
begin
Result := ChildNodes['OptionalName'].NodeValue;
end;
If you do a little googling, you will see that people are still asking questions about this even pretty recently. The suggested fix you will often discover is labor intensive if you have a lot of optional elements/attributes and will get wiped out if you rerun the XML Data Binding wizard:
if VarIsNull(ChildNodes['selected'].NodeValue) then
Result := 0; // or false or empty string, etc
else
Result := ChildNodes['selected'].NodeValue;
Hilariously in my mind, there is still an open ticket from 2002 about this issue: http://qc.embarcadero.com/wc/qcmain.aspx?d=2434
However, it seems the <insert-company-name-which-owns-Delphi> addressed this issue, probably years ago, and the fix/workaround is easy. You need to include the Variants unit and set the NullStrictConvert global variable to false:
NullStrictConvert := False
As the documentation states:
----------
NullStrictConvert determines the outcome of attempts to convert Null variants to other types.
If NullStrictConvert is true (default), attempting to convert a Null variant raises a EVariantTypeCastError, unless the conversion is to a custom variant that defines a conversion from Null. If NullStrictConvert is false, then conversion from Null follows the following rules
Now, the XML Data Binding code will silently convert NULL to 0, false, or empty string without a problem. I wanted to publicize this fix. I have been bitten by this exception more times than I can count and if I had known of the workaround, it would have made my life much easier.
----------
That’s it for today. I hope everyone is enjoying their Summer (or Winter in the southern hemisphere).
http://docwiki.embarcadero.com/Libraries/Berlin/en/System.Variants.Null
http://docwiki.embarcadero.com/Libraries/Berlin/en/System.Variants.EVariantTypeCastError
Thanks to CodeSmithing!
Delphi开发技巧: 修复XML数据绑定错误: “Could not convert variant of type (Null) into type…”!
最新推荐文章于 2023-08-11 14:27:15 发布