Cocoa:加载XML文件(数组);

Cocoa:加载XML文件(数组);,xml,arrays,cocoa,macos,Xml,Arrays,Cocoa,Macos,是否有一种方法可以加载XML文件并将其数据放入数组中例如: XML文件: <xml ...> <adressbook> <contact name="Name" phone="00000000"/> <contact name="Name2" phone="00000002"/> <contact name="Name3" phone="00000003"/> <contact name="Name

是否有一种方法可以加载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 00000000 4

提前感谢。

来源:

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的博客文章

代码可以在github上找到


Ben Sgro提供了一个处理属性的修复程序。

您知道如何修复[NSXMLDocument initWithData:options:error:]:nil参数,因为initWithXMLString在gdb上也返回了此错误,然后initWithData也返回了此错误。