使用 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?

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

希望对您有所帮助!