我一直在遵循
SWXMLHash
反序列化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,我创建了以下结构,它是一个可反序列化的XmlIndexer
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>
。运行上面的反序列化代码将在
节点[“handlingTime”]。值()
解决这个问题的一种方法是,每当我们访问XMLIndexer的键时,尝试捕捉异常,如果抛出异常,则将默认值传递给属性,这意味着键不存在。但我认为这不是最好的方法。
当XML缺少属性时,反序列化XML的最佳方法是什么?