c# - Deserialize empty XML element as Guid.Empty -
i have troubles deserializing.
<order> ... <cardnumber /> ... </order>
if use
<cardnumber>00000000-0000-0000-0000-000000000000</cardnumber>
it's working normally, in case when use <cardnumber />
- object not deserializing (
is there way deserialize empty element guid.empty?
property should mapped value of element:
[xmlelement(elementname = "cardnumber")] [jsonproperty("cardnumber")] public guid? cardnumber { get; set; }
same situation in json works , use guid.empty instead of empty element value
{ "cardnumber": "" }
the exception seeing explains problem clearly:
system.invalidoperationexception occurred message="there error in xml document (3, 3)." innerexception: system.formatexception message="guid should contain 32 digits 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)."
as stated, xmlserializer
not support deserializing empty string guid
. need conversion manually using surrogate property:
[xmlroot("order")] public class order { [xmlignore] [jsonproperty("cardnumber")] public guid? cardnumber { get; set; } [xmlelement(elementname = "cardnumber", isnullable = true)] [browsable(false), editorbrowsable(editorbrowsablestate.never), debuggerbrowsable(debuggerbrowsablestate.never)] [jsonignore] public string xmlcardnumber { { if (cardnumber == null) return null; else if (cardnumber.value == guid.empty) return ""; return xmlconvert.tostring(cardnumber.value); } set { if (value == null) cardnumber = null; else if (string.isnullorempty(value)) cardnumber = guid.empty; else cardnumber = xmlconvert.toguid(value); } } }
if need in many different types have guid?
properties, can extract surrogate type so:
[xmltype(anonymoustype = true, includeinschema = false)] public class xmlguid { [xmlignore] public guid guid { get; set; } [xmltext] public string xmlcardnumber { { if (guid == guid.empty) return null; return xmlconvert.tostring(guid); } set { if (string.isnullorempty(value)) guid = guid.empty; else guid = xmlconvert.toguid(value); } } public static implicit operator guid?(xmlguid x) { if (x == null) return null; return x.guid; } public static implicit operator xmlguid(guid? g) { if (g == null) return null; return new xmlguid { guid = g.value }; } public static implicit operator guid(xmlguid x) { if (x == null) return guid.empty; return x.guid; } public static implicit operator xmlguid(guid g) { return new xmlguid { guid = g }; } }
and use like:
[xmlroot("order")] public class order { [xmlelement(type = typeof(xmlguid), elementname = "cardnumber", isnullable = true)] [jsonproperty("cardnumber")] public guid? cardnumber { get; set; } }
here taking advantage of fact xmlelementattribute.type
property automatically picks implicit conversion defined guid?
, xmlguid
.
Comments
Post a Comment