我收到以下 XML IQ 并想在 iOS 中解析它。请帮忙!
<iq type="result">
<stories xmlns="success">
<storyid>1</storyid>
<title>THE TITLE</title>
<picture>BASE64EncodedStringOfImage</picture>
<storyid>2</storyid>
<title>Love At First Site</title>
<picture>BASE64EncodedStringOfImage</picture>
</stories>
</iq>
我尝试了下面的代码,但它不起作用。它获取 successStoryArray
中的值,但之后什么也没有。请帮忙!
NSXMLElement *stories = [iq elementForName:@"stories"];
NSArray *successStoryArray = [stories elementsForName:@"storyid"];
NSLog(@"successStoryArray: %@", successStoryArray);
for (NSXMLElement *i in successStoryArray)
{
NSXMLElement *title = [i elementForName:@"title"];
NSString *sTitle = [title stringValue];
NSLog(@"sTitle: %@", sTitle);
NSXMLElement *picture = [i elementForName:@"picture"];
NSString *sPicture = [picture stringValue];
NSLog(@"sPicture: %@", sPicture);
}
最佳答案
您正在迭代错误的元素。 NSArray *successStoryArray = [stories elementsForName:@"storyid"];
将得到两个元素:storyid 值为 1 和 storyid 值为 2。
然后您遍历这些元素并尝试提取标题和图片,但标题和图片不是 的子元素。标题和图片与storyid同级,都是.
有两种解决方法:
提取 3 个数组,每个包含 storyid、title 和 picture 的值
NSArray *successStoryArray = [stories elementsForName:@"storyid"];
NSArray *titleArray = [stories elementsForName:@"title"];
NSArray *pictureArray = [stories elementsForName:@"picture"];
然后您可以按顺序迭代它们并且项目将匹配
更好在我看来,通过将每个故事包装在一个元素中来更改 XML 的结构,如下所示:
<iq type="result">
<stories xmlns="success">
<story>
<storyid>1</storyid>
<title>THE TITLE</title>
<picture>BASE64EncodedStringOfImage</picture>
</story>
<story>
<storyid>2</storyid>
<title>Love At First Site</title>
<picture>BASE64EncodedStringOfImage</picture>
</story>
</stories>
</iq>
然后你可以这样做:
NSXMLElement *stories = [iq elementForName:@"stories"];
NSArray *successStoryArray = [stories elementsForName:@"story"];
NSLog(@"successStoryArray: %@", successStoryArray);
for (NSXMLElement *i in successStoryArray)
{
NSXMLElement *storyId = [i elementForName:@"storyId"];
NSString *sId = [storyId stringValue];
NSLog(@"sId: %@", sId);
NSXMLElement *title = [i elementForName:@"title"];
NSString *sTitle = [title stringValue];
NSLog(@"sTitle: %@", sTitle);
NSXMLElement *picture = [i elementForName:@"picture"];
NSString *sPicture = [picture stringValue];
NSLog(@"sPicture: %@", sPicture);
}
关于ios - iOS 中的 xmpp IQ XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23084798/