用空元素反序列化Xml [英] Deserialize Xml with empty elements

查看:79
本文介绍了用空元素反序列化Xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下XML:

<a>
    <b>2</b>
    <c></c>
</a>  

我需要将此xml反序列化为对象。所以,我写了下面的课。

I need to deserialize this xml to an object. So, i wrote the following class.

public class A
{
    [XmlElement("b", Namespace = "")]
    public int? B { get; set; }

    [XmlElement("c", Namespace = "")]
    public int? C { get; set; }

}

由于我使用的是nullables,因此我一直期待着,当反序列化上述xml时,我将获得具有空C属性的对象A。

Since i'm using nullables, i was expecting that, when deserialing the above xml, i would get an object A with a null C property.

相反,我得到了一个异常,告诉文档有错误。 / p>

Instead of this, i get an exception telling the document has an error.

推荐答案

missing 元素和 null 元素之间存在区别。

There's a difference between a missing element and a null element.

缺少的元素< a< b> 2< / b< / a> 。这里C将使用 DefaultValue 属性采用您指定的任何默认值,如果没有显式的默认值,则为null。

A missing element, <a><b>2</b></a>. Here C would take whatever default value you specify, using the DefaultValue attribute, or null if there's no explicit default.

空元素 a a b 2 2 / b> c xs:Nil ='true'/< / a 。

当您执行< a< b> 2< / b< c>< / c>< a /> xml序列化程序将尝试解析字符串。如果为空,则它将正确地失败。

When you do <a><b>2</b><c></c><a/> the xml serializer will try to parse string.Empty as an integer an will correctly fail.

提供程序正在生成无效的xml,如果使用XmlSerializer,则需要执行以下操作:

Since your provider is generating invalid xml you will need to do this, if using the XmlSerializer:

[XmlRoot(ElementName = "a")]
public class A
{
    [XmlElement(ElementName = "b")]
    public int? B { get; set; }

    [XmlElement(ElementName = "c")]
    public string _c { get; set; }

    public int? C
    {
        get
        {
            int retval;

            return !string.IsNullOrWhiteSpace(_c) && int.TryParse(_c, out retval) ? (int?) retval : null;
        }
    }
}

或使用DataContractSerializer稍好

or slightly better using the DataContractSerializer

[DataContract(Name="a")]
public class A1
{
    [DataMember(Name = "b")]
    public int? B { get; set; }

    [DataMember(Name = "c")]
    private string _c { get; set; }

    public int? C
    {
        get
        {
            int retval;

            return !string.IsNullOrWhiteSpace(_c) && int.TryParse(_c, out retval) ? (int?)retval : null;
        }
    }
}

尽管DataContractSerializer不会支持属性(如果有问题的话)。

although the DataContractSerializer doesn't support attributes if that's a problem.

这篇关于用空元素反序列化Xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆