For example I have class to serialize
[Serializable]
class Person
{
[XmlAttribute("name")]
string Name {get;set;}
}
I need to make Name attribute required. How to do this in .NET?
For example I have class to serialize
[Serializable]
class Person
{
[XmlAttribute("name")]
string Name {get;set;}
}
I need to make Name attribute required. How to do this in .NET?
First of all,
[Serializable]
is not used by the XML Serializer.Second, there is no way to make it required.
The best way to solve this is by having a separate XSD which you use to validate the XML before you pass it onto the
XmlSerializer
. The easiest way to work with XSD's andXmlSerializer
is to start off with an XSD, generate the code for theXmlSerializer
from this XSD and also use it to validate the XML.You can use this:
I believe you are confusing XML with an XSD. If you want your property to always have a value, initialize this property in the constructor, and throw an exception if anyone tries to set it to empty or null.
You could use the
XmlIgnoreAttribute
along with the<FieldName>Specified
pattern to throw an exception if the property is left blank or null. During serialization theNameSpecified
property will be checked to determine if the field should be rendered, so if the Name properties left null or empty an exception is thrown.