2014-04-15 74 views
0

我收到以下XML IQ並希望在iOS中解析它。請幫忙!xmpp iOS中的IQ XML解析

 <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); 

    } 
+0

什麼具有u試過?嘗試一下,如果你根本不知道從哪裏開始http://techglimpses.blogspot.in/2013/03/xml-parsing-in-ios-sample-code.html –

+0

@代理我已經添加了以上我所嘗試過的。 –

回答

1

您遍歷錯誤的元素。 NSArray *successStoryArray = [stories elementsForName:@"storyid"];將獲得兩個元素:值爲1的storyid和值爲2的storyid。 然後你遍歷這些元素並嘗試提取標題和圖片,但標題和圖片不是子元素。標題和圖片與storyid處於同一水平,他們是兒童。

有兩種方法來解決這個問題:

提取3個陣列,每個包含storyid,標題和照片的值

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); 

    }