Required attributes in XML serialization

2019-06-16 06:24发布

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?

5条回答
乱世女痞
2楼-- · 2019-06-16 06:54

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

Second, there is no way to make it required.

查看更多
迷人小祖宗
3楼-- · 2019-06-16 06:56

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.

查看更多
男人必须洒脱
4楼-- · 2019-06-16 06:58

You can use this:

[XmlElement(IsNullable = false)]
查看更多
成全新的幸福
5楼-- · 2019-06-16 07:09

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.

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;
    }
   }
}
查看更多
唯我独甜
6楼-- · 2019-06-16 07:19

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;
          }
    }
}
查看更多
登录 后发表回答