for Nullable Value types when serialized in XML I have added some types of NULL values ​​for my serializable class. ...">

Prevention <xsi: nil = "true"> for Nullable Value types when serialized in XML

I have added some types of NULL values ​​for my serializable class. I am serializing using XmlSerializer , but when the value is set to null , I get an empty node with xsi:nil="true" . This is the correct behavior I found in Xsi: nil Attribute Binding Support .

Is there a way to disable this option so that nothing is output when the value type is null ?

+8
serialization xml-serialization xml-nil
source share
6 answers

I had the same problem. Here is one of the places that I read about working with NULL value types, as well as serialization in XML: https://stackoverflow.com/a/464632/

they mention the use of inline templates, such as creating additional properties for types with a null value. for example, for a property named

 public int? ABC 

you must either add either public bool ShouldSerializeABC() {return ABC.HasValue;} or the public bool ABCSpecified { get { return ABC.HasValue; } } bool ABCSpecified { get { return ABC.HasValue; } }

i was only serialized for xml to be sent to stored proc sql, so I also avoided changing my classes. I am checking [not(@xsi:nil)] on all nullable elements in my .value () request.

+5
source share

I found that the public bool ABCSpecified was the only one that worked with .NET 4.0. I also had to add XmlIgnoreAttribute

Here is my complete solution for suppressing a String named ABC in the Web Reference Resource.cs file:

 // backing fields private string abc; private bool abcSpecified; // Added this - for client code to control its serialization // serialization of properties [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)] public string ABC { get { return this.abc; } set { this.abc= value; } } // Added this entire property procedure [System.Xml.Serialization.XmlIgnoreAttribute()] public bool ABCSpecified { get { return this.abcSpecified; } set { this.abcSpecified = value; } } 
+4
source share

I had to add the ShouldSerialize method to each Nullable value.

 [Serializable] public class Parent { public int? Element { get; set; } public bool ShouldSerializeElement() => Element.HasValue; } 
+2
source share

All meta methods, such as Specified or ShouldSerialize, are just a poor design for programming the Microsoft.Net XML framework. This becomes even more complicated if you do not have direct access to the classes you want to serialize.

In their serialization method, they should simply add an attribute of type ignoreNullable.

My current workaround is serializing xml and then just deleting all nodes having nil = "true" using the following function.

 /// <summary> /// Remove optional nullabe xml nodes from given xml string using given scheme prefix. /// /// In other words all nodes that have 'xsi:nil="true"' are being removed from document. /// /// If prefix 'xmlns:xsi' is not found in root element namespace input xml content is returned. /// </summary> /// <param name="xmlContent"></param> /// <param name="schemePrefix">Scheme location prefix</param> /// <returns></returns> public static String RemoveNilTrue(String xmlContent, String schemePrefix = "xsi") { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xmlContent); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDocument.NameTable); bool schemeExist = false; foreach (XmlAttribute attr in xmlDocument.DocumentElement.Attributes) { if (attr.Prefix.Equals("xmlns", StringComparison.InvariantCultureIgnoreCase) && attr.LocalName.Equals(schemePrefix, StringComparison.InvariantCultureIgnoreCase)) { nsMgr.AddNamespace(attr.LocalName, attr.Value); schemeExist = true; break; } } // scheme exists - remove nodes if (schemeExist) { XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//*[@" + schemePrefix + ":nil='true']", nsMgr); foreach (XmlNode xmlNode in xmlNodeList) xmlNode.ParentNode.RemoveChild(xmlNode); return xmlDocument.InnerXml; } else return xmlContent; } 
+1
source share

This is probably the least complicated answer, but I solved it for me when a simple string is replaced.

.Replace ("xsi: nil = \" true \ "," ");

I am still serializing the string. I can save the file later.

Saves all my XmlWriterSettings. Another solution I found, it ruined it :)

  private static string Serialize<T>(T details) { var serializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream()) { var settings = new XmlWriterSettings { Encoding = Encoding.GetEncoding("ISO-8859-1"), NewLineChars = Environment.NewLine, ConformanceLevel = ConformanceLevel.Document, Indent = true, OmitXmlDeclaration = true }; using (var writer = XmlWriter.Create(ms, settings)) { serializer.Serialize(writer, details); return Encoding.UTF8.GetString(ms.ToArray()).Replace(" xsi:nil=\"true\" ", ""); } } } 
0
source share

I did it like this:

  private bool retentionPeriodSpecified; private Nullable<int> retentionPeriod; [XmlElement(ElementName = "retentionPeriod", IsNullable = true, Order = 14)] public Nullable<int> RetentionPeriod { get => retentionPeriod; set => retentionPeriod = value; } [System.Xml.Serialization.XmlIgnore()] public bool RetentionPeriodSpecified { get { return !(retentionPeriod is null); } } 
0
source share

All Articles