代码之家  ›  专栏  ›  技术社区  ›  roundcrisis

XmlSerializer.Deserialize是否可以返回空值?

  •  4
  • roundcrisis  · 技术社区  · 15 年前

    我尝试了几种不同的方法来获取XmlSerializer。反序列化以返回空值。 但似乎不可能

    我尝试使用一个空的、格式错误的XML和格式良好的XML类。

    我可能遗漏了一些明显的东西,但这是可能的吗?

    为了澄清给一个可序列化的类MyClass,我希望通过以下类似的测试

    [Fact] //this is a the test attribute when using xUnit
    public void When_xml_Something_Then_serialize_returns_null()
    {
        string serializedObject = "<?xml version=\"1.0\" encoding=\"utf-8\"?><MyClass xmlns:xsi=\"http://www.w3asdsadasdasd.org/2001/XMLSchema-instance\"></MyClass>";
        using (var stringReader = new StringReader(serializedObject))
        {
            Assert.Null(new XmlSerializer(typeof(MyClass)).Deserialize(stringReader));
        }
    }
    

    在序列化字符串中尝试了不同的操作,我得到了一个异常或MyClass的空实例:( 谢谢 注意:这个问题有错别字,现在更正了

    注2:有关更详细的答案,请查看注释。

    2 回复  |  直到 15 年前
        1
  •  11
  •   John Saunders    11 年前

    对, Deserialize 当输入不包含预期的XML时,不能返回空值。当XML名称空间混淆时,经常会出现这种情况。如果输入包含具有预期名称的根元素,但名称空间不同,则返回空值。

    这在处理asmx Web服务或Web引用时经常会出现,尤其是针对rpc样式服务的Web引用,其中消息是用xsd描述的。 type 而不是根据 element .

        2
  •  0
  •   Sjoerd    15 年前

    表面上,你可以 view download .NET框架的system.xml部分的代码。这允许您查看源代码以确定它何时返回空值。

    推荐文章