Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required attributes in XML serialization

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?

like image 294
darja Avatar asked May 24 '10 02:05

darja


People also ask

What is the correct way of using XML serialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.

Which annotation is needed for serialization and deserialization of XML format?

XmlMapper Object It is used for the serialization and deserialization of the XML data. So, the first step for serializing and deserializing XML data is to create an instance of the XmlMapper class in the following way: XmlMapper mapper = new XmlMapper();

Which of the following attribute controls XML serialization of the attribute target as an XML root element?

XmlRootAttribute Class (System. Xml. Serialization) Controls XML serialization of the attribute target as an XML root element.

What does it mean to serialize XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.


2 Answers

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 the NameSpecified 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.

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

              return true;
          }
    }
}
like image 99
user3443886 Avatar answered Oct 07 '22 04:10

user3443886


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 and XmlSerializer is to start off with an XSD, generate the code for the XmlSerializer from this XSD and also use it to validate the XML.

like image 43
Pieter van Ginkel Avatar answered Oct 07 '22 05:10

Pieter van Ginkel