从xml中提取特定元素

时间:2013-04-15 13:46:02

标签: iphone ios objective-c nsxmlparser

我在我的iOS应用程序中实现了XML解析,但是我遇到了以下文件的问题:

<?xml version="1.0" encoding="UTF-8"?>
<AllJobs>
    <Mainjobs>
     <job1 name="simple">
     <Group name="one">
        <item name>"itemone"</item name>
        <item name>"itemtwo"</item name>
        <item name>"itemthree"</item name>
      </Group>
      <Group name="two">
        <item name>"itemfour"</item name>
        <item name>"itemfive"</item name>
        <item name>"itemsix"</item name>
      </Group>
    </job1>
    <job2 name="medium" />
    </job2>
    <job3 name="hard" />
    </job3>
    </Mainjobs>
</AllJobs>

我正在尝试解析“itemfour,itemfive,itemsix”的项目名称并在tableview中显示它们:

<Group name="two">
    <item>"itemfour"</item>
    <item>"itemfive"</item>
    <item>"itemsix"</item>
</Group>

我正在解析这样但它正在检索每个组标记中的所有项目名称:

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

    if([elementName isEqualToString:@"Alljobs"]){
        jobNameArray=[[NSMutableArray alloc]init];

    } else if ([elementName isEqualToString:@"Mainjobs"]) {
        //  self.itemDict = [[NSMutableDictionary alloc] init];
        object=[[parseObject alloc]init];
        dict=[[NSMutableDictionary alloc] init];
    } else if ([elementName isEqualToString:@"Group"]) {
        if ([str isEqualToString:@"Two"]) {
            currentElement=nil;
            currentElement=[[NSMutableString alloc]init];
        }
    } else if([elementName isEqualToString:@"item"]) {
        str=[attributeDict objectForKey:@"name"];
        NSLog(@"the attribute string is %@",[attributeDict objectForKey:@"name"]);
    }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if(string) {
        [currentElement appendString:string];
        NSLog(@"  the element00000000%@", currentElement);
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:    (NSString *)namespaceURI qualifiedName:(NSString *)qName {

    if([elementName isEqualToString:@"Mainjobs"]){
        NSLog(@"the array count is %i",[jobNameArray count]);
    } else if([elementName isEqualToString:@"Job1"]) {

    }

    if([elementName isEqualToString:@"</item>"]) {
        NSLog(@"element ---------%@",elementName);

        [jobNameArray addObject:str];
    }
}

1 个答案:

答案 0 :(得分:1)

XML标记名称不能包含空格。

涉及<item name>的结果未定义。