Required Attributes in XML Serialization

For example, I have a class for serialization

[Serializable] class Person { [XmlAttribute("name")] string Name {get;set;} } 

I need to specify the Name attribute. How to do it in .NET?

+7
xml-serialization
source share
5 answers

First of all, [Serializable] not used by the XML serializer.

Secondly, there is no way to make this necessary.

+4
source share

You can use XmlIgnoreAttribute with the <FieldName>Specified template to throw an exception if the property is left blank or null. During serialization, the NameSpecified property will be checked to determine whether this field should be displayed, so if Name properties are left blank or empty, an exception is thrown.

 class Person { [XmlElement("name")] string Name { get; set; } [XmlIgnore] bool NameSpecified { get { if( String.IsNullOrEmpty(Name)) throw new AgrumentException(...); return true; } } } 
+3
source share

The best way to solve this is to create a separate XSD that you use to validate the XML before passing it to the XmlSerializer . The easiest way to work with XSD and XmlSerializer is to start with XSD, generate the code for XmlSerializer from this XSD and also use it to validate XML .

+1
source share

You can use this:

 [XmlElement(IsNullable = false)] 
0
source share

I believe that you are mixing XML with XSD. If you want your property to always have a value, initialize this property in the constructor and throw an exception if someone tries to set it to empty or empty.

 class Person { private string _Name = "Not Initialized"; [XmlAttribute("name")] string Name { get { return _Name;} set { if(value == null || value==string.Empty) throw new ArgumentException(...); _Name = value; } } } 
-2
source share

All Articles