XmlSerializerはNullable< int>に逆シリアル化できますか?
-
08-07-2019 - |
質問
nil =" true"
とマークできる要素を含むXMLメッセージを、 int?
型のプロパティを持つクラスにデシリアライズしたかった。動作させる唯一の方法は、 IXmlSerializable
を実装する独自の NullableInt
型を記述することでした。より良い方法はありますか?
すべての問題とその解決方法を書き上げました私のブログで。
解決
nil =" true"のプレフィックスを付ける必要があると思います。 XmlSerializerがnullにデシリアライズするための名前空間を持つ。
<?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"/>
他のヒント
私の修正は、ノードを前処理し、「nil」を修正することです。属性:
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のClone()を使用します。
非常に怠exceptionalな方法。いくつかの理由で脆弱ですが、私のXMLはそのような迅速で汚い修正を保証するのに十分なほど単純です。
xmlStr = Regex.Replace(xmlStr, "nil=\"true\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"");
所属していません StackOverflow