Web API - closing the tag instead of i: nil

I am using the Web API with DataContract serialization. The result is as follows:

 <Data> <Status> <Date>2014-08-13T00:30:00</Date> <ID>312</ID> <Option>No Limitation</Option> <Value i:nil="true" /> </Status> <Status> <Date>2014-08-13T01:00:00</Date> <ID>312</ID> <Option>No Limitation</Option> <Value i:nil="true" /> </Status> <Status> <Date>2014-08-13T01:30:00</Date> <ID>312</ID> <Option>No Limitation</Option> <Value i:nil="true" /> </Status> <Status> <Date>2014-08-13T02:00:00</Date> <ID>312</ID> <Option>No Limitation</Option> <Value i:nil="true" /> </Status> 

I managed to remove all the extra namespaces by doing:

 [DataContract(Namespace="")] public class Status 

But the only attribute remains the i:nil attribute. What should I do to remove the i: nil attribute?

+5
source share
2 answers

What you want is to make the code β€œthink” so that instead of a null value, there really is an empty string. You can do this by being a little smart with a getter property (see below). Be sure to add a comment explaining why you are doing this, so other people who will support the code know what is going on.

 [DataContract(Namespace = "")] public class Status { [DataMember] public DateTime Date { get; set; } [DataMember] public int ID { get; set; } [DataMember] public string Option { get; set; } private string value; [DataMember] public string Value { get { return this.value ?? ""; } set { this.value = value; } } } 
+1
source

You need to set the EmitDefaultValue property in the DataMember

 [DataMember(EmitDefaultValue = false)] 

Be sure not to set this attribute for members for which IsRequired = true .

Edit

You can also iterate the XML manually and remove the nil attributes using LINQ 2 XML :

 XNamespace i = "http://www.w3.org/2001/XMLSchema-instance"; XDocument xdoc = XDocument.Load(@"XmlHere"); // This may be replaced with XElement.Parse if the XML is in-memory xdoc.Descendants() .Where(node => (string)node.Attribute(i + "nil") == "true") .Remove(); 
+3
source

Source: https://habr.com/ru/post/1200514/


All Articles