0
我一直在使用SWXMLHash的示例來反序列化XML文件。這是合作得非常好,但我不知道如何處理的情況下,當XML輸入不完整:使用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,我創建下面的結構,其爲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」。運行上面的反序列化的代碼將在節點[「handlingTime」]拋出異常。值()
一種方法來解決這個問題是要努力趕上,每當我們訪問XMLIndexer的關鍵異常,並通過在如果引發異常,則表示該屬性的默認值不存在。但我認爲這不是最好的方法。
當XML缺少屬性時,反序列化XML的最佳方法是什麼?
嘿大衛,那確實解決了問題。謝謝你的幫助! – Mantracker