Cocoa: Loading a XML File (array);
Is there a way that I can load a XML File and put its data into an array for exemple:
The XML File:
<xml ...>
<adressbook>
<contact name="Name" phone="00000000"/>
<contact name="Name2" p开发者_高级运维hone="00000002"/>
<contact name="Name3" phone="00000003"/>
<contact name="Name4" phone="00000004"/>
</adressbook>
Now what I have to to if I want each attribute in one array lets say:
NSArray* name; NSArray* phone;
I want basically to make each array holds (consecutively) the XML Attributes. In this case it would be like:
name would hold:
Name Name2 Name3 Name4
And phone: 00000000 000000002 000000003 000000004
Thanks in advance.
Source:
NSXMLDocument* doc = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL fileURLWithPath:@"/folder/with/sample.xml"] options:0 error:NULL];
NSMutableArray* objects = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* descriptions = [[NSMutableArray alloc] initWithCapacity:10];
NSXMLElement* root = [doc rootElement];
NSArray* objectElements = [root nodesForXPath:@"//object" error:nil];
for(NSXMLElement* xmlElement in objectElements)
[objects addObject:[xmlElement stringValue]];
NSArray* descElements = [root nodesForXPath:@"//description" error:nil];
for(NSXMLElement* xmlElement in descElements)
[descriptions addObject:[xmlElement stringValue]];
NSLog(@"%@", objects);
NSLog(@"%@", descriptions);
[doc release];
[objects release];
[descriptions release];
Sample XML-file:
<?xml version="1.0" encoding="UTF-8"?>
<items>
<item id="0">
<object>First Object</object>
<description>Description One</description>
</item>
<item id="1">
<object>Second Object</object>
<description>Description Two</description>
</item>
</items>
Feel free to have a look at my blog entry below about simplified xml
http://www.memention.com/blog/2009/10/31/The-XML-Runner.html
The code is available at github
https://github.com/epatel/EPXMLParsers
Ben Sgro supplied a fix for handling attributes.
精彩评论