Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

c# - Deserialize Xml with empty elements

Consider the following XML:

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

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; }

}

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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 null element <a><b>2</b><c xs:Nil='true'/></a>. Here you will get null.

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.

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;
        }
    }
}

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;
        }
    }
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...