gpt4 book ai didi

ios - 使用 SWXMLHash 反序列化 xml 时处理丢失的属性

转载 作者:行者123 更新时间:2023-11-28 15:23:56 25 4
gpt4 key购买 nike

我一直在关注 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 的键时 try catch 异常,如果抛出异常(这意味着键不存在),则将默认值传递给该属性。不过,我认为这不是最佳方法。

当 XML 缺少属性时反序列化 XML 的最佳方法是什么?

最佳答案

handlingTime 属性的声明从 Int 更改为 Int?,如下所示:

let handlingTime: Int?

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

希望这对您有所帮助!

关于ios - 使用 SWXMLHash 反序列化 xml 时处理丢失的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45553183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com