如何使用带有不同节点的NSXMLParser解析XML?

问题描述:

我知道它可能看起来像XML解析帖子的副本,但我真的不能理解节点和委托方法的行为。我有一个XML ..如何使用带有不同节点的NSXMLParser解析XML?

<?xml version="1.0" encoding="UTF-8"?> 
<ParticipantService> 
    <Response> 
     <CourseProperties> 
      <CourseTitle>AICC_Flash_Workshop_PPT_to_web_examples</CourseTitle> 
      <CourseCode>123456</CourseCode> 
      <Availability>Open</Availability> 
      <Status>In Progress</Status> 
      <ImageLink>HTTP://lmsstaging.2xprime.com/images/inprogress_icon.png</ImageLink> 
      <CategoryCode>0</CategoryCode> 
      <CategoryDesc>General</CategoryDesc> 
     </CourseProperties> 
     <CourseProperties> 
      <CourseTitle>Behaviours</CourseTitle> 
      <CourseCode>OBIUS</CourseCode> 
      <Availability>Open</Availability> 
      <Status>In Progress</Status> 
      <ImageLink>HTTP://lmsstaging.2xprime.com/images/inprogress_icon.png</ImageLink> 
      <CategoryCode>0</CategoryCode> 
      <CategoryDesc>General</CategoryDesc> 
     </CourseProperties> 
     <CourseProperties> 
      <CourseTitle>Customer Service Skills (Part - one)</CourseTitle> 
      <CourseCode>css_1</CourseCode> 
      <Availability>Open</Availability> 
      <Status>In Progress</Status> 
      <ImageLink>HTTP://lmsstaging.2xprime.com/images/inprogress_icon.png</ImageLink> 
      <CategoryCode>0</CategoryCode> 
      <CategoryDesc>General</CategoryDesc> 
     </CourseProperties> 

....

我的要求是,以存储相关课程内容到相应的数组。所以我宣布了6个nsmutablearray,但却对如何从XMl中检索数据感到困惑。我这样

想出来的foundCharacters方法,我追加字符串的值作为

videoUrlLink = [NSMutableString stringWithString:string]; 

和didEndElement方法

if ([elementName isEqualToString:@"CourseTitle"]) { 
     [courseDetailList addObject:string]; 

    } 

但在XML我能够结束仅在数组中存储一个值。请让我知道我是否在某个地方出了问题?

我假设你有一个名为Course类和Course对象都有titlecodeavailability等特性。

使iVar currentCourse

然后,在你parser:didStartElement:namespaceURI:qualifiedName:attributes:(注:没有开始,没有结束!)方法:

if ([elementName isEqualToString:@"CourseProperties"]) { 
    //create a new course object 
    currentCourse = [[Course alloc] init]; 
} 

这使上下文后面的课程的所有属性。在didEndElement:方法,你基本上所有的课程属性做到这一点:

if ([elementName isEqualToString:@"CourseTitle"]) { 
    [currentCourse setTitle:string]; 
} 

而且,最后但并非最不重要的,一旦CourseProperties结束标记被发现,保存在某个地方新课程(也didEndElement:):

if ([elementName isEqualToString:@"CourseProperties"]) { 
    //create a new course object 
    [allMyCourses addObject:currentCourse]; 
    currentCourse = nil; 
} 
+0

在这种情况下如何从存储的数据中检索值?我的意思是如何获得所有课程名称,可用性,状态e.t.c ....? –

+0

你已经提到在didEndElement:方法中为currentCourse添加字符串。但是在这个元素中,你将不会拥有字符串属性。你可以检查一下吗? –