Search code examples
objective-cxmlparsingnsarray

Extract array from XML dictionary


Is it possible to extract an ordered array of keys from the XML file below:

Basically what I want is an array that looks like this and in this order: ["key1","key2","myKey3","key4","key5"]

The problem is that if I convert to NSDictionary first and then loop through the keys I lose the order.

I was hoping to be able to do this without changing the web server.

Thanks in advance

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>key1</key>
    <array>
        <string></string>
        <string>title1</string>
        <string>disabled</string>
    </array>
    <key>key2</key>
    <array>
        <string></string>
        <string>title2</string>
        <string>disabled</string>
    </array>
    <key>myKey3</key>
    <array>
        <string></string>
        <string>title3</string>
    </array>
    <key>key4</key>
    <array>
        <string></string>
        <string>title4</string>
        <string>disabled</string>
    </array>
    <key>key5</key>
    <array>
        <string></string>
        <string>title5</string>
        <string>disabled</string>
    </array>
</plist>

Solution

  • You could utilize NSXMLParser. You need to implement NSXMLParserDelegate and in the parser:didStartElement: if elementName is equal to "key", then in the next parser:foundCharacters: call you add the key value into an NSMutableArray. At the end you get an ordered array of keys.

    When you have your ordered keys, you can use them to iterate through the NSDictionary (dict below) that you have in order:

    for (NSString *key in orderedKeys) {
        NSArray *properties = dict[key];
        ...
    }
    

    See this for a concrete code example - NSXMLParser Simple Example