【问题标题】:Can XmlSerializer deserialize into a Nullable<int>?XmlSerializer 可以反序列化为 Nullable<int> 吗?
【发布时间】:2010-09-23 08:11:21
【问题描述】:

我想将包含可标记为nil="true" 的元素的XML 消息反序列化为具有int? 类型属性的类。我可以让它工作的唯一方法是编写我自己的实现IXmlSerializableNullableInt 类型。有没有更好的方法?

我写了完整的问题以及我解决它的方法on my blog

【问题讨论】:

    标签: xml-serialization nullable xml-nil


    【解决方案1】:

    我认为您需要在 nil="true" 前面加上一个命名空间,以便 XmlSerializer 反序列化为 null。

    MSDN on xsi:nil

    <?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"/>
    

    【讨论】:

    • 谢谢菲尔,这很好。现在我只需要让提供消息的人添加命名空间...
    • 别担心 SCOA :-P 如果你不能从源头更改 XML(听起来你可以),你可以通过 XSLT 转换来添加我认为的命名空间......跨度>
    • 是的,JENP,事实证明,在源代码中执行此操作很棘手,因为它是一个 Rails 应用程序,使用to_xml 生成 xml。此外,将 xsi: 添加到 type 属性会使 .NET 查找名为 array 的类型,该类型不存在。所以最后坚持使用我的NullableInt 类型会更容易。
    • 我有完全相同的问题,无法更改 api,可能会走 XSLT 路线(尽管我并没有走得太远)
    【解决方案2】:

    我的解决方法是预处理节点,修复任何“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()。

    【讨论】:

    • 这对我来说效果很好,谢谢。并明确用于 Rails 消费。我确实做了一些调整来检查非空属性:XmlAttribute nilAttribute = null; if (@this.Attributes != null) { nilAttribute = @this.Attributes["nil"]; }
    【解决方案3】:

    非常懒惰的做法。由于多种原因,它很脆弱,但我的 XML 足够简单,足以保证如此快速而肮脏的修复。

    xmlStr = Regex.Replace(xmlStr, "nil=\"true\"", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"");
    

    【讨论】:

      猜你喜欢
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 2010-11-20
      • 2023-04-05
      相关资源
      最近更新 更多