2

Here I am currently working on a program that will serialize an XML file asp.net object. My problem is that I can not find the attribute that makes it mandatory to have a tag in the XML file.

You will find below the definition of my object.

[System.SerializableAttribute()]
public class EchangeIdentification
{
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("agrement")]
    public string Agrement{ get; set; }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("cvi")]
    public string NumeroCvi { get; set; }

    /// <remarks/>
    [Required]
    [XmlElement("siret")]
    public string Siret { get; set; }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Space
  • 124
  • 1
  • 13

2 Answers2

1

As far as I know, there is no way to declaratively force elements and attributes to be required using the XmlSerializer. C# object properties that can be null are always optional.

A few observations

[Serializable] is not used by the XML Serializer.


There is no way to make it required using the XML Serializer, but if you don't have to use XmlSerializer? DataContractSerializer provides the following option:

[DataMember(IsRequired = true)]

You don't need the "Attribute" name in the code, your code could look like this

[Serializable]
public class EchangeIdentification
{
    [XmlElement("agrement")]
    public string Agrement{ get; set; }

    [XmlElement("cvi")]
    public string NumeroCvi { get; set; }

    [XmlElement("siret")]
    public string Siret { get; set; }
}
Sprotty
  • 5,676
  • 3
  • 33
  • 52
0

Define "serialize an XML file asp.net object" and "makes it mandatory to have a tag in the XML". It all depends on how you're using this class.

Are you using it as a deserialization container, into which you will deserialize XML you receive? Then create an XSD schema, and validate the incoming XML before (or rather during) serialization. See Validating an XML against referenced XSD in C#.

On the other hand, if the user of this code is assigning properties of an instance of this class at runtime, and you serialize it through XmlSerializer, you could validate the output after serializing. See the linked question above, and Can I fail to deserialize with XmlSerializer in C# if an element is not found?.

Alternatively, you could implement serialization callbacks and create a validation method that throws an exception if [Required] properties have the default value for their type.

I'd go with the XSD route either way.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272