簡體   English   中英

使用SWXMLHash反序列化xml時處理缺少的屬性

[英]Handling missing properties when deserializing xml using SWXMLHash

我一直在遵循SWXMLHash上的示例反序列化XML文件。 它工作得很好,但是我不確定在XML輸入不完整的情況下如何處理情況:

例如,假設XML輸入是這樣的:

<shippingInfo>
            <shippingServiceCost currencyId="USD">0.0</shippingServiceCost>
            <shippingType>Free</shippingType>
            <shipToLocations>US</shipToLocations>
            <expeditedShipping>true</expeditedShipping>
            <oneDayShippingAvailable>false</oneDayShippingAvailable>
            <handlingTime>1</handlingTime>
</shippingInfo>

為了反序列化此XML,我創建了以下結構,該結構是XMLIndexerDeserializable

import SWXMLHash

struct ShippingInfo: XMLIndexerDeserializable
{
    let currencyId: String
    let shippingServiceCost: Double
    let shippingType: String
    let shipToLocations: String
    let expeditedShipping: Bool
    let oneDayShippingAvailable: Bool
    let handlingTime: Int

    static func deserialize(_ node: XMLIndexer) throws -> ShippingInfo 
    {
        return try ShippingInfo(
            currencyId: node["shippingServiceCost"].value(ofAttribute: "currencyId"),
            shippingServiceCost: node["shippingServiceCost"].value(),
            shippingType: node["shippingType"].value(),
            shipToLocations: node["shipToLocations"].value(),
            expeditedShipping: node["expeditedShipping"].value(),
            oneDayShippingAvailable: node["oneDayShippingAvailable"].value(),
            handlingTime: node["handlingTime"].value()
        )
    }
}

上面的代碼可以正常工作,直到shippingInfo XML缺少一個元素為止,如下所示:

<shippingInfo>
            <shippingServiceCost currencyId="USD">0.0</shippingServiceCost>
            <shippingType>Free</shippingType>
            <shipToLocations>Worldwide</shipToLocations>
            <expeditedShipping>false</expeditedShipping>
            <oneDayShippingAvailable>false</oneDayShippingAvailable>
</shippingInfo>

上面的第二個XML缺少屬性“ handlingTime” 運行上面的反序列化代碼將在node [“ handlingTime”]。value()處引發異常

解決此問題的一種方法是,每當我們訪問XMLIndexer的鍵時嘗試捕獲異常,如果拋出異常(表示該鍵不存在),則將默認值傳遞給屬性。 我認為這不是最好的方法。

當XML缺少屬性時,反序列化XML的最佳方法是什么?

將您的handlingTime屬性的聲明從Int更改為Int? ,就像這樣:

let handlingTime: Int?

它必須可以為空,以便反序列化可以支持不存在的值。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM