Ignoring null value in XML serialization

I have an xml part that looks something like

<SubscriptionProduct> <SubscriptionProductIdentifier> <SubscriptionProductIdentifierType> <SubscriptionProductIDType>01</SubscriptionProductIDType> <ID>123456</ID> <Value>AAAA</Value> </SubscriptionProductIdentifierType> <SubscriptionProductIdentifierType xsi:nil="true" /> </SubscriptionProductIdentifier> <SubscriptionProductDescription /> </SubscriptionProduct> 

As you can see, SubscriptionProductIdentifierType is a collection and in this case contains only one element.
How to ignore the second empty element?

I tried adding ignore xml, however it deletes the whole collection, and I want the second element in the collection to be deleted if there is no data.

 [System.Xml.Serialization.XmlIgnoreAttribute()] public SubscriptionProductIdentifierType[] SubscriptionProductIdentifier { get { return this.subscriptionProductIdentifierField; } set { this.subscriptionProductIdentifierField = value; } } 

Any help would be greatly appreciated.

Regards Zal

+4
source share
2 answers

There is not one item in your collection, but two, one of which is null

just filter null elements at the time of adding or even before returning, depending on your business logic

 public SubscriptionProductIdentifierType[] SubscriptionProductIdentifier { get { return this.subscriptionProductIdentifierField.Where(s=>s!=null).ToArray(); } ... } 

Hope this helps

+1
source

XmlIgnoreAttribute will ignore the element, not just the elements that are zeros in the array. If you don’t have the ability to filter the results or remove the null value of the node earlier, then save the local variable to hold the filtered results and lazy loading.

 private SubscriptionProductIdentifierType[] _subscriptionProductIdentifierField = null; private SubscriptionProductIdentifierType[] _filteredSubscriptionProductIdentifier = null; public SubscriptionProductIdentifierType[] SubscriptionProductIdentifier { get { return this._filteredSubscriptionProductIdentifier ?? ( _filteredSubscriptionProductIdentifier = Array.FindAll( this._subscriptionProductIdentifierField, delegate(SubscriptionProductIdentifierType t) { return t != null; } )); } set { this._subscriptionProductIdentifierField = value; this._filteredSubscriptionProductIdentifier = null; } } 
0
source

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


All Articles