我一直在关注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 的最佳方法是什么?