John Livermore
John Livermore

Reputation: 31313

.NET Xml serializer optional attributes

Given the following code...

[XmlType("Field")]
public class SearchField
{
    [XmlAttribute("alias")]
    public string Alias;

    [XmlAttribute("entity")]
    public string Entity;
}

Alias is an optional field for us, but the deserializer throws when the "alias" attribute is missing from the xml. How do you make it optional? Is a schema required?

Upvotes: 7

Views: 11889

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Weird, because the following program works fine for me, without any throwings:

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[XmlType("Field")]
public class SearchField
{
    [XmlAttribute("alias")]
    public string Alias;

    [XmlAttribute("entity")]
    public string Entity;
}

class Program
{
    static void Main()
    {
        using (var reader = new StringReader("<Field entity=\"en\" />"))
        {
            var serializer = new XmlSerializer(typeof(SearchField));
            var s = (SearchField)serializer.Deserialize(reader);
            Console.WriteLine(s.Alias);
            Console.WriteLine(s.Entity);
        }
    }
}

As you can see the alias attribute is omitted from the input XML and yet no problem deserializing.

Upvotes: 13

Related Questions