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

标签 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 姓名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/

相关文章:

xml - 在 OpenXML sdk2 中以编程方式计算公式中的单元格值

c++ - C++中的二维步长数组

php - json_encode 不双引号 NULL ; cocoa touch 不当

java - 如何在Zxing Scanner Camera View中添加按钮

javascript - 在 Node.js 中保存 XML 文件

java - 如何从具有动态条目的文件中拆分

arrays - Angular-数组forEach索引

objective-c - UPnP 端口映射,服务不接受连接

iphone - 使用 CocoaLumberjack 和 ZXingWidget 的架构 i386 的 undefined symbol

java - 当 namespace 前缀更改时,如何验证 XML 签名?