Click here to Skip to main content
15,880,392 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

(* I'm using LinqPad to test this, that's why you can see the .Dump() call at the end of my sample)

In this code, I'm getting "Instance validation error: '' is not a valid value for claves_sexo", because it is empty:

C#
void Main()
{
  string xmlString = "<Products><Product><Id>1</Id><Name>My XML product</Name><Sexo></Sexo></Product></Products>";

  XmlSerializer serializer = new XmlSerializer(typeof(List<Product>), new XmlRootAttribute("Products"));

  StringReader stringReader = new StringReader(xmlString);

  List<Product> productList = (List<Product>)serializer.Deserialize(stringReader);

  productList.Dump();

}

public class Product
{
	public int Id { get; set; }
	public string Name { get; set; }
	
	public claves_sexo Sexo {get;set;}
}

public enum claves_sexo
{
	HO,
	MU,
	ND
}


I would like the Sexo member of Product, to be assigned the value ND = 2 for the enum when it's not informed.

Thanks in advance,

Roger

What I have tried:

I've been playing with the XmlIgnore attribute and created another member to import the value for the empty tag as a String, and assign it to Sexo member, but I didn't succeeded.
Posted
Updated 12-Apr-19 7:20am

1 solution

I wrote extension methods to return a default value if the element didn't exist. Go to this CP article: Downloads: SQLXAgent - Jobs for SQL Express - Part 1 of 6[^]

and scroll down to SqlxCommon\FileExtensions, and look for ExtendLinqToXML.cs

BTW, I generally don't us the built-in .Net serialization stuff, because I want more control oevr what's happening. Yeah, it can be a hassle, but wwell, you know.
 
Share this answer
 
v2
Comments
Roger Tranchez 14-Apr-19 11:14am    
Thanks for your answer; Anyway, I will apply the simplest solution I've found here in order to avoid changing too much existing code:
https://stackoverflow.com/questions/55658526/deserializing-empty-xml-tags-in-c-sharp-with-enumerations/55660275#55660275

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900