gpt4 book ai didi

ios - XML 到 NSDictionary 的 NSArray

转载 作者:行者123 更新时间:2023-11-29 13:44:14 25 4
gpt4 key购买 nike

我有一个类似这样的 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>

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

我找到了 Parse XML item "Category" into an NSArray with NSDictionary <solved/>但似乎无法让它发挥作用。如果有人有任何想法如何执行此操作或将数据导入我的应用程序的更好方法,我们将不胜感激。

最佳答案

仅适用于 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";
}
}

关于ios - XML 到 NSDictionary 的 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8101878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com