I need to mark some fields as required to be writen in XML file, but no success. I have a configuration class with ~30 properties, this is why i cannot envelope all properties like this
public string SomeProp
{
get { return _someProp; }
set
{
if (_someProp == null)
throw new ArgumentNullException("value");
_someProp = value;
}
}
and null is valid value from code, but not from XML. I'm trying to use XmlAttribute
, but it doesn't affect like I expected (IOException when deserialising).
For example this code:
[XmlElement(IsNullable = true)]
public String Name { get; set; }
[XmlElement(IsNullable = true)]
public String Description { get; set; }
is pretty valid when Name
and Description
tags are missing.
clarification:
Class:
public class MyClass
{
[XmlElement(IsNullable = true)]
public String Name { get; set; }
[XmlElement(IsNullable = true)]
public String Description { get; set; }
}
XML:
<?xml version="1.0"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>hello</Name>
</MyClass>
code:
MyClass deserialize = (MyClass)new XmlSerializer(my.GetType()).Deserialize(new FileStream("result.xml", FileMode.Open));
Console.WriteLine(deserialize.Name);
Console.WriteLine(deserialize.Description);
result: deserialization is successful, Description is null
expected: exception, Description tag not found.