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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With