chenyunguiMilook / SwiftyXML

The most swifty way to deal with XML data in swift 5.
MIT License
101 stars 27 forks source link

Read value by attributes? #6

Closed babyghost-ys closed 6 years ago

babyghost-ys commented 6 years ago

Hey,

First of all, I must say this is a great control.

But I would like to ask is there anyway to access the value by using attributes? Like in your example, let color0 = xml["product"]["catalog_item"]["size"]["color_swatch"][1].string //"Burgundy"

Can I access the value "Burgundy" without using the number (1 in this case), but with the file name "burgundy_cardigan.jpg"? Thanks!

chenyunguiMilook commented 6 years ago

let image = xml["product"]["catalog_item"]["size"]["color_swatch"][1]["@image"].string //"burgundy_cardigan.jpg"

this will the attribute you want.

babyghost-ys commented 6 years ago

Sorry. I mean I still want the value "Burgundy", but access using the file name. Like may be?

let image = xml["product"]["catalog_item"]["size"]["color_swatch"]["burgundy_cardigan.jpg"].string

chenyunguiMilook commented 6 years ago

because it does not cache as dictionary, you may need to do as following: if let swatches = xml["product"]["catalog_item"]["size"]["color_swatch"].xmlList {

var dict = [String : String]()

for xml in swatches {
    if  let key = xml["@image"].string,
        let value = xml.string {
        dict[key] = value
    }
}

dict["burgundy_cardigan.jpg"] //"Burgundy"

}

babyghost-ys commented 6 years ago

Thanks! Problem solved!