有没有一种方法可以加载 XML 文件并将其数据放入数组中,例如:
XML 文件:
<xml ...>
<adressbook>
<contact name="Name" phone="00000000"/>
<contact name="Name2" phone="00000002"/>
<contact name="Name3" phone="00000003"/>
<contact name="Name4" phone="00000004"/>
</adressbook>
现在,如果我想要一个数组中的每个属性,我必须这样做:
NSArray* 名称; NSArray* 电话;
我基本上想让每个数组(连续)保存 XML 属性。在这种情况下,它会像:
名称将包含:
姓名 姓名2 姓名3 名称4
电话: 00000000 000000002 000000003 000000004
提前致谢。
最佳答案
来源:
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];
示例 XML 文件:
<?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>
关于xml - Cocoa:加载 XML 文件(数组);,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5044482/