0
我實現XML解析在我的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」,並在實現代碼如下顯示它們:
<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];
}
}
'- 「itemfour」
'是無效的XML。 –
Cyrille
而你最好使用XPath解析器,它對你的任務來說會更簡單。 – Cyrille
從您的解析代碼,看起來像你期待- 標籤的名稱屬性。但是你的名字屬性沒有價值。 xml應該是
- some_thing_here
–
lostInTransit