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

时间:2011-02-18 17:25:56

标签: 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="Name4" phone="00000004"/>
</adressbook>

现在,如果我想在一个数组中使用每个属性,我必须说:

NSArray *名字; NSArray *电话;

我希望基本上让每个数组保持(连续)XML属性。在这种情况下,它将是:

名称将成立:

名称 名称2 NAME3 NAME4

和电话: 00000000 000000002 000000003 000000004

提前致谢。

2 个答案:

答案 0 :(得分:2)

来源:

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>

答案 1 :(得分:1)

请随时查看我的博客条目,了解有关简化的xml

的信息

http://www.memention.com/blog/2009/10/31/The-XML-Runner.html

代码可在github上找到

https://github.com/epatel/EPXMLParsers

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