XML到NSDictionarys的NSArray

时间:2011-11-12 01:39:51

标签: ios xml nsarray nsdictionary

我有一个XML文件:

<houses>
<house>
<title>123 Main St</title>
<address>123 Main St, Georgetown Washingon D.C.</address>
<photo>http://www.photo.com/images/1.jpg</photo>
<photo>http://www.photo.com/images/2.jpg</photo>
<photo>http://www.photo.com/images/3.jpg</photo> 
<photo>http://www.photo.com/images/4.jpg</photo>
</house>

<house>
<title>1234 Main St</title>
<address>1234 Main St, Georgetown Washingon D.C.</address>
<photo>http://www.photo.com/images/1.jpg</photo>
<photo>http://www.photo.com/images/2.jpg</photo>
<photo>http://www.photo.com/images/3.jpg</photo> 
<photo>http://www.photo.com/images/4.jpg</photo>
</house>

并且需要一种方法来使用NSDictonarys填充NSArray的<house>标记之间的信息。

我找到了Parse XML item "Category" into an NSArray with NSDictionary <solved/>但似乎无法使其发挥作用。如果有人有任何想法如何做到这一点或更好的方式将数据导入我的应用程序和帮助将非常感谢。

1 个答案:

答案 0 :(得分:1)

仅适用于MacOS:

这是代码:

NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"xml" ofType:@"xml"];
NSString *xml = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:nil];
NSXMLDocument *xmlDocument = [[[NSXMLDocument alloc] initWithXMLString:xml options:0 error:nil] autorelease];
NSMutableArray *array = [NSMutableArray array];

for (NSXMLElement *node in [xmlDocument.rootElement nodesForXPath:@"//house" error:nil])
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    NSMutableArray *photos = [NSMutableArray array];

    for (NSXMLElement *subNode in node.children)
{
        if ([subNode.name isEqualToString:@"photo"])
            [photos addObject:subNode.stringValue];
        else 
            [dict setObject:subNode.stringValue forKey:subNode.name];
    }

    [dict setObject:photos forKey:@"photos"];
    [array addObject:dict];
}

NSLog(@"%@", array);

这是输出:

(
{
    address = "123 Main St, Georgetown Washingon D.C.";
    photos =         (
        "http://www.photo.com/images/1.jpg",
        "http://www.photo.com/images/2.jpg",
        "http://www.photo.com/images/3.jpg",
        "http://www.photo.com/images/4.jpg"
    );
    title = "123 Main St";
},
    {
    address = "1234 Main St, Georgetown Washingon D.C.";
    photos =         (
        "http://www.photo.com/images/1.jpg",
        "http://www.photo.com/images/2.jpg",
        "http://www.photo.com/images/3.jpg",
        "http://www.photo.com/images/4.jpg"
    );
    title = "1234 Main St";
}
}