简体   繁体   English

忽略XML序列化中的空值

[英]Ignoring the null value in XML Serialization

I have a piece of xml that looks something like 我有一块看起来像的xml

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

As you can see the SubscriptionProductIdentifierType is a collection and in this case only contains one item. 如您所见,SubscriptionProductIdentifierType是一个集合,在这种情况下只包含一个项目。
How do I ignore the second empty item? 如何忽略第二个空项目?

I've tried adding the xml ignore, however it removes the entire collection and I only want the second item in the collection removed if there is no data. 我已经尝试添加xml忽略,但它删除了整个集合,我只希望在没有数据的情况下删除集合中的第二个项目。

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

Any help would be very much appreciated. 任何帮助将非常感谢。

Kind Regards Zal 亲切的问候Zal

There is not one item in your collection but two, one of which is null 您的集合中没有一个项目,但有两个项目,其中一项为空

just filter null items during addition, or even before return, depending on your business logic 只是在添加期间,甚至在返回之前过滤空项,具体取决于您的业务逻辑

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

Hope this helps 希望这可以帮助

XmlIgnoreAttribute will ignore the member, not just items that are null within an array. XmlIgnoreAttribute将忽略该成员,而不仅仅是数组中为null的项。 If you have no way of filtering the results or removing the null node ahead of time, then store a local variable to hold the filtered results and lazy load it. 如果您无法提前过滤结果或删除空节点,则存储局部变量以保存过滤结果并延迟加载它。

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;
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM