-2

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>
JP Aquino
  • 3,946
  • 1
  • 23
  • 25
  • Don't think about order in a Dictionary, or you misunderstood its purpose. Order shouldn't be important in a dictionary because access is through key not index. And that seems more like a plist file (easy transformation method) than a "true" xml (parsing is more complex). – Larme May 24 '18 at 20:40
  • Thanks but maybe you misunderstood my question. I am looking to convert that XML file into an array. If I convert it to a dictionary and then to an array it won't keep the order b/c the dictionary is an unordered collection. That is from a plist true but it's exactly the same file that I asked to be posted on the web server so I def. need to parse. – JP Aquino May 24 '18 at 20:47

1 Answers1

2

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

battlmonstr
  • 5,841
  • 1
  • 23
  • 33
  • Interesting thanks. I will check this out tomorrow and let you know how it works. – JP Aquino May 24 '18 at 21:10
  • Thank you. This worked perfectly. It's cool that most people actually want to be helpful here instead of just downvoting for the heck of it. – JP Aquino May 25 '18 at 14:32