Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 519
John Livermore Avatar asked Nov 01 '11 20:11

John Livermore


People also ask

Is XmlSerializer thread safe?

Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application.

Why do we use XmlSerializer class?

XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.

What does XML serializer do?

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.

Which class should be used to serialize an object in XML format?

XmlIgnoreAttribute Class (System. Xml. Serialization) Instructs the Serialize(TextWriter, Object) method of the XmlSerializer not to serialize the public field or public read/write property value.


1 Answers

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.

like image 134
Darin Dimitrov Avatar answered Sep 20 '22 03:09

Darin Dimitrov