Search code examples
xmlswiftswxmlhash

Get Value From XML Response Swift


I am using a Swift xml parser library located Here. I am looking to get a specific value from the below XML that has a certain value.

The below XML shows a list of apps installed on a device and then lists information about each app; like version and app size. Each <deviceSw> is a different app on the device. I am looking to get the Version value from the com.fiberlink.browser app. Side note is that I can't just get the second app on the device because some devices might have com.fiberlink.browser listed as the third app or fourth app. Is there a way to sort through the XML for the value of com.fiberlink.browser and then get the Version value for it?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<deviceSoftwares>
    <deviceSw>
        <swAttrs>
            <key>Application ID</key>
            <type>string</type>
            <value>com.fiberlink.maas360forios</value>
        </swAttrs>
        <swAttrs>
            <key>Version</key>
            <type>string</type>
            <value>2.40.60</value>
        </swAttrs>
        <swAttrs>
            <key>AppDataSize</key>
            <type>string</type>
            <value>2.09</value>
        </swAttrs>
    </deviceSw>
    <deviceSw>
        <swAttrs>
            <key>Application ID</key>
            <type>string</type>
            <value>com.fiberlink.browser</value>
        </swAttrs>
        <swAttrs>
            <key>Version</key>
            <type>string</type>
            <value>1.30.45</value>
        </swAttrs>
        <swAttrs>
            <key>AppDataSize</key>
            <type>string</type>
            <value>0.51</value>
        </swAttrs>
    </deviceSw>

EDIT:

I have tried the below code to loop through the keys and maybe do the logic to sort through after but it returns nil value.

for elem in xml["deviceSoftwares"]["deviceSw"].all {
    print(elem["swAttrs"]["key"].element!.text!)
}

EDIT 2:

I changed my code to the following:

for elem in xml["deviceSoftwares"]["deviceSw"]["swAttrs"].all {
    print(elem["key"].element!.text)
}

and nothing prints out, its just a blank output window.


Solution

  • After much struggle, the below code works:

    var count: Int = 0
    var stop = false
                    
    for elem in xml["deviceSoftwares"]["deviceSw"].all {
        for elem2 in elem["swAttrs"].all {
            if stop == false {
                count += 1
                if (elem2["value"].element!.text) == "com.fiberlink.browser" {
                    stop = true
                }
            }
        }
    }
    

    This allows you to look through the XML and get the position of the app value that you need. Then you can add more code to target the position and get the value.