【问题标题】:Parsing XML in iOS在 iOS 中解析 XML
【发布时间】:2014-05-13 19:22:08
【问题描述】:

我在- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq收到以下IQ

<iq xmlns='jabber:client'
    type='result'
    to='abc@xyz/6cbb843f'>
<questions>
<question id='56'
          text='Favorite Food'>
<option id='1'>
chinese
</option>
<option id='2'>
indian
</option>
<option id='3'>
thai
</option>
</question>
<question id='57'
          text='Music'>
<option id='4'>
eastern
</option>
<option id='5'>
pop
</option>
<option id='6'>
classical
</option>
</question>
<question id='58'
          text='Movies/TV Shows'/>
</questions>
</iq>

我想从 iOS 中的上述 IQ 中检索问题及其选项。我尝试了下面的代码,但它只给了我问题,我无法检索他们的选项。请帮忙。

NSXMLElement *Questions = [iq elementForName:@"questions"];
            NSArray *questions = [Questions elementsForName: @"question"];

            NSLog(@"Questions in IQ %@ are: %@", [iq attributeStringValueForName:@"questions"], questions);

【问题讨论】:

    标签: ios xmpp nsxmlparser xmppframework


    【解决方案1】:
    1. 您的自定义 XML 格式不正确,questions 应绑定到某个命名空间,例如 ... 所有子元素都将被视为来自 my:questions:namespace 的元素,并且 XML 格式正确。

    2. 你把元素和属性搞混了,questionquestions 的子元素,但textquestion 的一个属性,而“Favorite food”是text 属性的字符串值@ 987654328@ 元素与id=56。而optionquestion 的子元素。因此,要列举问题和答案,请尝试:

      NSXMLElement *questions = [iq elementForName:@"questions"];
      NSArray *questionsArray = [questions elementsForName: @"question"];
      for (id question in questionsArray) {
          NSLog(@"Question '%@':", [question attributeStringValueForName:@"text"]);
          for (id option in [question elementsForName:@"option"]) {
              NSLog(@"option: %@", [option stringValue])
           }
      }
      

    【讨论】:

    • 太好了,我在“didReceiveIQ”中收到了 IQ,我想在视图控制器中显示这些问题,而不是应用程序委托。这是否可以在另一个视图控制器中执行上述检索问题和选项的功能?如果是的话,您能否建议我一个解决方案。
    • didReceiveIQXMPPStreamDelegate 协议的方法,在您的视图控制器中实现它并使用[xmppStream addDelegate:...] 将该控制器添加到XMPPStream 委托列表中。
    • XMPPIQ 数据包的情况下 - 如果数据包已处理,则唯一的单个委托应处理响应并返回YES,如果其他委托应处理它,则返回NO。因此,您应该在单个委托中处理您的 questions 响应,保存在您自己的结构中并在需要时传递给视图控制器
    • 是的,你是对的。您还可以将它们存储在 Core Data 中并从您的视图控制器等中获取。
    • for (id question in questionArray) {NSLog(@"%@", [question attributeStringValueForName:@"id"])}
    猜你喜欢
    • 2012-08-11
    • 2012-08-05
    • 2013-02-08
    • 2014-05-22
    • 2010-11-04
    • 2014-04-17
    • 2017-01-26
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多