XmlSerializer的可以反序列化到可空的?
-
08-07-2019 - |
题
我想反序列化含有可被标记nil="true"
与类型的属性int?
一类的元素的XML消息。我能得到它的工作的唯一办法是写一个实现NullableInt
我自己IXmlSerializable
类型。有没有更好的办法做到这一点?
我写了完整的问题,我解决了它的我的博客上。
解决方案
我想你需要的前缀零=“真”,一个命名空间,以便向XmlSerializer的deserialise为空。
<?xml version="1.0" encoding="UTF-8"?>
<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="array">
<entity>
<id xsi:type="integer">1</id>
<name>Foo</name>
<parent-id xsi:type="integer" xsi:nil="true"/>
其他提示
我的解决办法是预处理的节点,固定任何“无”属性:
public static void FixNilAttributeName(this XmlNode @this)
{
XmlAttribute nilAttribute = @this.Attributes["nil"];
if (nilAttribute == null)
{
return;
}
XmlAttribute newNil = @this.OwnerDocument.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance");
newNil.Value = nilAttribute.Value;
@this.Attributes.Remove(nilAttribute);
@this.Attributes.Append(newNil);
}
我夫妇这与子节点递归搜索,因此对于任何给定的XmlNode(或XmlDocument的),我可以发出反序列化前的一个电话。如果你想保持原来的内存结构修改,用的XmlNode的克隆()工作。
在异常懒惰方式做到这一点。它是有很多原因,但脆弱的我的XML是足够简单,以保证这样一个快速和肮脏的修复。
xmlStr = Regex.Replace(xmlStr, "nil=\"true\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"");
不隶属于 StackOverflow